Special Characters

suggest change

To 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")
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents