Basic Usage

suggest change

There are several considerations when implementing Regular Expressions in Swift.

let letters = "abcdefg"
let pattern = "[a,b,c]"
let regEx = try NSRegularExpression(pattern: pattern, options: [])
let nsString = letters as NSString
let matches = regEx.matches(in: letters, options: [], range: NSMakeRange(0, nsString.length))
let output = matches.map {nsString.substring(with: $0.range)}
//output = ["a", "b", "c"]

To get a range length that accounts for all UTF-16 code units, convert the input string to an NSString.

For safety, match inside a do-catch block so an invalid pattern can fail. The comma in [a,b,c] is a literal member of the set, not a separator.

let numbers = "121314"
let pattern = "1[2,3]"
do {
    let regEx = try NSRegularExpression(pattern: pattern, options: [])
    let nsString = numbers as NSString
    let matches = regEx.matches(in: numbers, options: [], range: NSMakeRange(0, nsString.length))
    let output = matches.map {nsString.substring(with: $0.range)}
    output
} catch let error as NSError {
    print("Matching failed")
}
//output = ["12", "13"]

Regular-expression helpers are often put in an extension so the concern stays separate.

Feedback about page:

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



Table Of Contents