RegEx in Swift? RegEx in Swift? swift swift

RegEx in Swift?


Unfortunately, Swift is lacking regex literals. But the external link you are referring to exposes 2 ways to use regex.

  1. Make a class wrapper around NSRegularExpression and use this class.
  2. Calling the Foundation method rangeOfString:options: with RegularExpressionSearch as option. This in Swift.

The 2nd way is cleaner and simpler to implement.

The method method definition in Swift

func rangeOfString(_ aString: String!,options mask: NSStringCompareOptions) -> NSRange

You can use it with regex matching as:

let myStringToBeMatched = "ThisIsMyString"let myRegex = "ing$"if let match = myStringToBeMatched.rangeOfString(myRegex, options: .RegularExpressionSearch){    println("\(myStringToBeMatched) is matching!")}

Here's Apple's documentation on rangeOfString()


I faced the same problem. So, I wrote a small wrapper - https://gist.github.com/ningsuhen/dc6e589be7f5a41e7794. Add the Regex.swift file in your project and add "Foundation" framework if not already added. Once you do that, you can use the replace and match methods as follows.

"+91-999-929-5395".replace("[-\\s\\(\\)]", template: "") //replace with empty or remove"+91-999-929-5395".match("[-\\s\\(\\)]") //simple match - returns only true or false, not the matched patterns.


Another easy option is to use NSPredicate if what you're interesting in is pure validation (true/false):

Here's a quick Regex to match a Canadian Postal code:

func isCAZipValid(_ zip: String) -> Bool {    return NSPredicate(format: "SELF MATCHES %@", "^([A-Z]\\d[A-Z])(\\s|-)?(\\d[A-Z]\\d)$")             .evaluate(with: zip.uppercased())                }