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


2 answers


Use a pointer in the first to indicate the number of characters that will be allowed.

^(?=.{5,6}$)[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$

      



DEMO

+2


source


(?!^-)(?!.*?-$)(?!.*?--)^[a-zA-Z0-9-]{5,6}$

      

Try it. Check out the demo.



http://regex101.com/r/kM7rT8/15

+1


source







All Articles