I'm searching a text for a specific pattern using regex and it seems to work fine until I want to include a ":"
the function I use to find the text is:
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
The example array I use to test the pattern is:
var textstringarray = ["10:50 - 13:40","ABC"]
And here is the loop that checks the different items:
for myString in textstringarray{
let matched2 = matches(for: "[0-9][0-9][:][0-9][0-9] [-] [0-9][0-9][:][0-9][0-9]", in: myString)
if !matched2.isEmpty{
print(matched2)
}
}
I expect it to return only the first item, but the Log in Playground only says
invalid regex: The value “[0-9][0-9][:][0-9][0-9] [-] [0-9][0-9][:][0-9][0-9]” is invalid
So far I figured out that the problem the second [:] is, because when I delete it everything works fine. Anyone any idea, what I could do? Thanks a lot