1

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

MotoxX
  • 917
  • 1
  • 7
  • 13
  • 2
    `\d{2}:\d{2} - \d{2}:\d{2}`? No need to put `:` inside a set. Same goes for `-`. You can just declare them literally (they're not special characters in regex - well `-` is but only inside sets and `:` is if accompanied by other characters such as `(?:)` but that's beside the point with your case) – ctwheels Jan 03 '18 at 18:26
  • 2
    Your function [looks familiar](https://stackoverflow.com/a/27880748/1187415) :) – Martin R Jan 03 '18 at 19:08
  • Brilliant! That solved it! Thanks a lot ctwheels! I just got rid of the brackets and now its working! – MotoxX Jan 04 '18 at 18:34

1 Answers1

0

Maybe it thinks [: ... :] is an invalid posix character class? Seems like a bug to me.

Does [\:] fix it? (Though there's no need to use a character class for a single character; you could just have : instead of [:].)

ysth
  • 96,171
  • 6
  • 121
  • 214