SamGhatak
SamGhatak

Reputation: 1493

Regex match hangs my program

We have an application where we are using the following RegEx to validate email.

private string _regularExpression = @"^(("".+?"")|([0-9a-zA-Z](((\.(?!\.))|([-!#\$%&'\*\+/=\?\^`\{\}\|~\w]))*[0-9a-zA-Z])*))@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9}$";
Regex _reg = new Regex(_regularExpression);

However we have a incorrect email in source:

abcd1090ihavenoidea.what.going.wrong.here

for which the program hangs. We are still unable finding out which part we are doing wrong here?

Upvotes: 1

Views: 803

Answers (2)

Quinn
Quinn

Reputation: 4504

EDIT Although I don't think regex is the right tool for validating emails, if OP prefers to use it, I found the following long pattern from HERE, which claims the best match. And the site is dedicated for regex solutions:

^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$

REGEX DEMO.

Also take a look at this site: Stop Validating Email Addresses With Regex

Upvotes: 1

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

The program hangs because with this regex you get a Catastrophic backtracking. It stopped on Regex 101 after 121 628 steps. I try to lower the input string to see how catastrophic it was: it took 88 063 steps to understand that abcd1090ihav.w is not a valid email.

Since you're using , you may read :

Upvotes: 4

Related Questions