[ACCEPTED]-RegEx for allowing alphanumeric at the starting and hyphen thereafter-regex
If you do not want to match mutiple dashes 2 after eachother:
^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$
This will match: a
, a-a
, aaa-a
, aaa-a-aaa-a-aaa-a
, etc
But 1 not: -
, -a
, a-
, a--a
, a-a-a-
, a-a--a
, etc.
^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$
0
I would propose:
^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$
This also matches strings 1 of the length 1.
Here is the POSIX + look-akead variant of 10 doing it:
^[[:alnum:]](?:[[:alnum:]-](?!-$))*$
This also allows just one character 9 as a match. It is not so readable, though. ;-)
Note 8 that [[:alnum:]]
is a shorthand predefined character 7 class equivalent to [a-zA-Z0-9]
, being more efficient, but 6 otherwise interchangeable. Not every regex 5 flavor knows these POSIX classes, use the 4 traditional form if you like.
Here is one 3 that does not allow multiple consecutive 2 hyphens, and it is shorter:
^(?:[[:alnum:]]+(?:-(?!$))?)+$
and it's non-POSIX 1 form:
^(?:[a-zA-Z0-9]+(?:-(?!$))?)+$
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.