Special Characters
suggest changeTo match a special character, escape it in the pattern. In a Swift string that backslash is itself escaped, so \. is written "\\.".
Characters to escape include:
(){}[]/\+*$>.|^?
This example matches three kinds of opening brackets. output exists only inside the do block:
let specials = "(){}[]"
let pattern = "(\\(|\\{|\\[)"
do {
let regEx = try NSRegularExpression(pattern: pattern, options: [])
let nsString = specials as NSString
let matches = regEx.matches(in: specials, options: [], range: NSMakeRange(0, nsString.length))
let output = matches.map { nsString.substring(with: $0.range) }
// output == ["(", "{", "["]
} catch {
print("Matching failed")
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents