Sahil Kapoor Sahil Kapoor - 1 year ago 109
iOS Question

How to use NSRegularExpression in Swift?

I have written this function in String Extension and can't figure out the error.

func isEmail() -> Bool {
let regex = NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", options: [.CaseInsensitive])

return regex.firstMatchInString(self, options: nil, range: NSMakeRange(0, characters.count)) != nil

The error is:

Call can throw, but it is not marked with 'try' and the error is not handled

Answer Source

NSRegularExpression(pattern:) throws an error if the pattern is invalid. In your case, the pattern is fixed, so an invalid pattern would be a programming error.

This is a use-case for the "forced-try" expression with try!:

extension String {
    func isEmail() -> Bool {
        let regex = try! NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$",
            options: [.CaseInsensitive])

        return regex.firstMatchInString(self, options:[],
            range: NSMakeRange(0, utf16.count)) != nil

try! disables the error propagation so that the method does not throw an error (which the caller has to catch). It will abort with a runtime exception if the pattern is invalid, which helps to find programming errors early.

Note also that NSRange() counts the length of NSString, i.e. the number of UTF-16 code points, so characters.count should be utf16.count, otherwise it might crash e.g. with Emoji characters.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download