Reputation: 25141
I'm a bit puzzled with a particular regex that is seemingly simple.
The match must be a string with only a-z, A-Z, 0-9 and must have at least one occurence of the '-' character anywhere in the string.
I have [a-zA-Z0-9-]+
but the problem is, it will also match those without the '-' character.
ABC123-ABC //should match
ABC123ABC //shouldn't match.
Upvotes: 13
Views: 29809
Reputation: 34395
Peter's solution: (^([a-zA-Z0-9]*-[a-zA-Z0-9]*)+$
) performs well when given a string that matches. However, this expression experiences Catastrophic Backtracking when presented with a non-matching string such as:
aa-aa-aa-aa-aa-aa-aa-aa-aa-aa-aa-aa%
Here are regular expressions which avoid this problem:
^[a-zA-Z0-9]*-[-a-zA-Z0-9]*$ # Match one or more -
^([a-zA-Z0-9]*-){5}[a-zA-Z0-9]*$ # Match exactly 5 -
^([a-zA-Z0-9]*-){1,5}[a-zA-Z0-9]*$ # Match from 1 to 5 -
Upvotes: 4
Reputation: 93030
This should work:
^([a-zA-Z0-9]*-[a-zA-Z0-9]*)+$
Also if you want to have exactly 135 hyphens:
^([a-zA-Z0-9]*-[a-zA-Z0-9]*){135}$
or if you want to have at least 23 hyphens but not more than 54 hyphens:
^([a-zA-Z0-9]*-[a-zA-Z0-9]*){23,54}$
You get the point :)
Upvotes: 31