Swift regex: does a string match a pattern?
Swift version 3 solution:
if string.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil ...
Swift version 2 solution:
if string.rangeOfString(pattern, options: .RegularExpressionSearch) != nil ...
Example -- does this string contain two letter "o" characters?
"hello world".rangeOfString("o.*o", options: .RegularExpressionSearch) != nil
Note: If you get the error message 'String' does not have a member 'rangeOfString'
, then add this before: import Foundation
. This is because Foundation provides the NSString methods that are automatically bridged to the Swift String class.
import Foundation
Thanks to Onno Eberhard for the Swift 3 update.
The solutions mentioned above didn't work for me anymore, so I'm posting my solution here (I used an extension for String):
extension String { func matches(_ regex: String) -> Bool { return self.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil }}
Example:
if str.matches("^[a-zA-Z0-9._-]{1,30}$") { //...}
To get the syntax you actually ask about, you can easily define a new operator which wraps the bridged NSString
functionality:
infix operator =~ {}func =~(string:String, regex:String) -> Bool { return string.rangeOfString(regex, options: .RegularExpressionSearch) != nil}"abcd" =~ "ab*cd""abcd" =~ "abcde+"