Simple Regex, match any string with at least one hyphen
I'm a bit puzzled with a particular regex that is seeming开发者_如何学编程ly 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.
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 :)
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 -
Here's a simple regex:
^(?=.*-)[a-zA-Z0-9-]+$
精彩评论