Regularly match alphanumeric characters with a possible dash in the middle only
I managed to get this far:
^[a-zA-Z0-9]+(?:--?[a-zA-Z0-9]+)*$
but the above expression does not limit the length as I need it. I need a pattern that only matches 5-6 characters. So, this is how it should turn out:
safety (valid)
safet- (invalid)
s-a-fe (valid)
-safet (invalid)
s7-45 (valid)
s--fs (invalid)
Consecutive hyphens are not valid. Invalid leading and trailing dashes. The total length, including any hyphens, must be 5-6 characters. I tried to replace my with +
ranges ( {5,6}
) but no luck. I appreciate any help.
Another route I tried was:
^[A-Z0-9][A-Z0-9-]{3,4}[A-Z0-9]$i
which seems nice and efficient, but it allows for sequential hyphens.
+3
source to share