Abdalla AlHaj Hasan Abdalla AlHaj Hasan - 2 months ago 8
Swift Question

Can't do regex matching in Swift

I am working on a Swift project and I need to use this regex to check email is valid or not but when the app start the checking the app crash and give me this error:


NSInternalInconsistencyException', reason: 'Can't do regex matching, reason: Can't open pattern U_REGEX_MISSING_CLOSE_BRACKET


This is my REGEX:

^(([^<>()[\\]\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+[\\.]*)+[a-zA-Z]{2,}))$

Answer

Check unescaped brackets in your regex pattern:

let pattern
= "^(([^<>()[\\]\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))"
//    [     [                 ]     [     [                 ]
+ "@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+[\\.]*)+[a-zA-Z]{2,}))$"
//       [   ]        [   ]        [   ]        [   ]            [            ] [   ]   [      ]

You have some mismatching brackets [ ] in the first half of your pattern.

In some dialects of regex, you have no need to escape [ between [ and ], but in some other dialects, you need it.

Try adding some escapes to your regex:

let pattern
= "^(([^<>()\\[\\]\\.,;:\\s@\\\"]+(\\.[^<>()\\[\\]\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))"
//    [     ^^                  ]     [     ^^                  ]
+ "@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+[\\.]*)+[a-zA-Z]{2,}))$"
//       [   ]        [   ]        [   ]        [   ]            [            ] [   ]   [      ]
Comments