Swift regular expressions

I want to test user input to see if the entire input matches the following regex. How do I do that with Swift?

[a-zA-Z]+@[a-zA-Z]+.[a-zA-Z]


Solution 1:

Look like you are trying to verify email addresses. Try this:

let test = "[email protected]"

do {
    let regex = try NSRegularExpression(pattern: "[a-zA-Z0-9]+@[a-zA-Z0-9]+.[a-zA-Z]", options: [])
    if regex.firstMatchInString(test, options: [], range: NSMakeRange(0, test.utf16.count)) != nil {
        print("matched")
    } else {
        print("not matched")
    }
} catch let error as NSError {
    print(error.localizedDescription)
}

NSRegularExpression is still carrying a lot of the ObjC legacy behind it so it's pretty verbose to use.

Solution 2:

Here's a way to do it in Swift without NSRegularExpression. You still need to import Foundation.

let email = "[email protected]"
if let _ = email.range(of: #"[a-zA-Z]+@[a-zA-Z]+.[a-zA-Z]"#,
                                 options: .regularExpression) {
    print("We have a match!")
}