Imad
Imad

Reputation: 189

regular expression making browser unresponsive

I am using this regular expression to set system name. But if length is 30 and I enter a '.' then browser becomes unresponsive. Can any one please point out anything wrong with this regex:

/^[a-zA-Z0-9]+([\.\-]?[a-zA-Z0-9]+)*$/

Will appreciate any help.

Upvotes: 2

Views: 392

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626950

The issue is the catastrophic backtracking. The point is the you have an optional pattern [\.\-]? and that makes the regex engine perform too many backtracking steps to understand that there is no match (when the string is long and the last non-matching char is . or -). Here is a demo of a short string causing the issue.

You just need to remove the ? quantifier in this case:

/^[a-zA-Z0-9]+([.-][a-zA-Z0-9]+)*$/

Here is the demo showing how the regex fails gracefully.

The point is that each subsequent subpattern shouldn't match the same text.

Also, . and - do not have to be escaped in the [.-].

If you are not using the captured value, replace ( with (?: to make the group non-capturing.

Upvotes: 2

Related Questions