RegEx for resolving alphanumeric values ​​at the start and hyphen after that

I had a requirement when the first character in the text field should be an alphabetic number and then I can resolve the hyphen after that in JavaScript. Also at the end should not be allowed

+7
regex
source share
4 answers

If you do not want to match the dash with the mishas after eachother:

 ^ [a-zA-Z0-9] + (- [a-zA-Z0-9] +) * $

This will match: a , aa , aaa-a , aaa-a-aaa-a-aaa-a , etc.
But not: - , -a , a- , a--a , aaa- , aa--a , etc.

+12
source share
 ^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$ 
+7
source share

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]+(?:-(?!$))?)+$ 
+5
source share

I would suggest:

 ^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$ 

This also matches lines of length 1.

+5
source share

All Articles