Swift string regex

How to check if string is matched specific regex in Swift?

Our goal is use it easy, like this:

let string = "4916474932438684"
if string =~ "^4[0-9]{6,}$" {
    // Here is Visa
}

Regular expression in string can be done with range function:

if string.range(of: "^4[0-9]{6,}$", options: [.regularExpression]) {
    //
}

Using extension we can provide more convenience function:

/// String extensions
extension String {
    /// Returns true if `String` matches regex `pattern`.
    /// - parameter pattern: pattern to search
    func matches(_ pattern: String) -> Bool {
        return self.range(of: pattern, options: [.regularExpression]) != nil
    }
}

New matches function:

if string.matches("^4[0-9]{6,}$") {
    //
}

The last step is to create infix operator for our function:

/// String regex pattern matching operator
infix operator =~ {}
/// Returns true if `string` matches regular expression `pattern`.
/// - parameter string: string to test
/// - parameter pattern: pattern to search
func =~ (string: String, pattern: String) -> Bool {
    return string.matches(pattern)
}

Опубликовано: Июль 18, 2016 ~ Swift, Regex