let regex1 = "(\\ud83d\\udc68)"
let regex2 = "(\\ud83d[\\udc68-\\udc69])"
"".capturedGroupsFull(forRegex: regex1)
// returns 1 match: [(.0 "", .1 {0, 2})]
"".capturedGroupsFull(forRegex: regex2)
// returns nil
Why is the first line returning one match and the second line no match?
- Both regular expressions work fine on regex101 (e.g. set to
javascript and use second regex as
(\ud83d[\udc68-\udc69])
). - I am working with Swift 4.0.
- This regex
"(\\ud83d[\\udc68])"
will also returnnil
when testing in Playground.
Below you can find the full code I use to retrieve the matches.
extension String {
func capturedGroupsFull(forRegex regex: String) -> [(String, NSRange)]? {
let expression: NSRegularExpression
do {
expression = try NSRegularExpression(pattern: regex, options: [.caseInsensitive])
} catch {
return nil
}
let nsString = self as NSString
let matches = expression.matches(in: self, options: [], range: NSRange(location:0, length: nsString.length))
guard let match = matches.first else { return nil }
var results = [(String, NSRange)]()
for match in matches {
let range = match.range
let matchedString = nsString.substring(with: range)
results.append((matchedString, range))
}
return results
}
}