NOVA99 NOVA99 - 5 months ago 15
Swift Question

Check if string matches regex pattern Swift 2.2

I have this regex (

([A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}
) for email adresses and I am trying to make a function to check if a string correspondes to it.
I already tried

func matches() -> Bool
{
let emailRegex : String = "([A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(self) //I use self because this is an extension of String
}


and

func matches() -> Bool
{
let emailRegex : String = "([A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return self.rangeOfStringrangeOfString(emailRegex, options: .RegularExpressionSearch) != nil
}


but they either give me a runtime error (with NSPredicate) or say that every single email adress is invalid (with .rangeOfString)

I found also a Regex class declaration at this link that is written in Swift 1.x (but I can easily convert it to Swift 2.x to build it) but it doesn't work neither.

I googled up and down without finding a working or understandable method (I'm a bit new to Swift) so my question is: how do I check if a string matches a regex in Swift 2?

Answer

There appears to be a (somewhat strange) opening parenthesis at the start of your regular expression. Remove that and see what happens:

let emailRegex : String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"

works for me.


NB: validating email using a regular expression is generally a bad idea. It's better to try and send the email, and see what error you get.
For example, your regular expression will fail for some of the examples given at the Wikipedia page on email addresses (in particular quoted strings, such as "very.unusual.@.unusual.com"@example.com_.