Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to apply this regex to NSRegularExpression?

\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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading