\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b
https://www.regular-expressions.info/email.html
How do I apply the regex above to an NSRegularExpression in Swift? I get a SIGABRT error when I run this code.
func validEmail(from input: String) -> String? {
do {
let regex = try NSRegularExpression(pattern: #"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b"#,
options: .caseInsensitive)
let range = NSRange(location: 0, length: input.utf16.count)
let matches = regex.matches(in: input, options: [], range: range)
if let match = matches.first {
let matchedRange = match.range(at: 1)
if let swiftRange = Range(matchedRange, in: input) {
return String(input[swiftRange])
}
}
} catch {
print(error)
}
return nil
}
let email = "a@a.com"
print(validEmail(from: email) ?? "invalid email")
>Solution :
You can simply use string range(of:) and pass .regularExpression to options. To match lowercased as well you just need to add a-z to your regex:
func validEmail(from input: String) -> String? {
guard let range = input.range(of: #"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"#, options: .regularExpression) else { return nil }
return String(input[range])
}
let email = "a@a.com"
print(validEmail(from: email) ?? "invalid email") // a@a.com
To just literally fix the error you need to pass zero to the range:
match.range(at: 0)