特殊字元

要匹配特殊字元,應使用雙反斜槓 \. becomes \\.

你必須轉義的角色包括

(){}[]/\+*$>.|^?

以下示例獲得三種左括號

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)}
} catch let error as NSError {
    print("Matching failed")
}
//output = ["(", "{", "["]