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.
In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.
You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).
The dash - is a meta character if not in the beginning or at the end of a character class, e.g. [0-9] will match any digits between 0 and 9. If you only want to match 0, dash or 9, you need to escape the dash: [0\-9]
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With