Here is the POSIX + look-akead option:
^[[:alnum:]](?:[[:alnum:]-](?!-$))*$
It also allows you to use only one character. However, this is not so clear .; -)
Note that [[:alnum:]] is a shorthand predefined character class equivalent to [a-zA-Z0-9] , more efficient, but otherwise interchangeable. Not every regular expression flavor knows these POSIX classes; use the traditional form if you want.
Here is one that does not allow multiple consecutive hyphens, and it is shorter:
^(?:[[:alnum:]]+(?:-(?!$))?)+$
and this is a non-POSIX form:
^(?:[a-zA-Z0-9]+(?:-(?!$))?)+$
Tomalak
source share