A.Munzer
A.Munzer

Reputation: 1990

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,}))$

Upvotes: 0

Views: 2462

Answers (1)

OOPer
OOPer

Reputation: 47876

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,}))$"
//       [   ]        [   ]        [   ]        [   ]            [            ] [   ]   [      ]

Upvotes: 1

Related Questions