Reputation: 25
Sorry if my question can be simple but, I'm blocked.
I was looking for a way to validate a regex that match several cases :
I've tried this : ^[a-zA-Z0-9]{1}(?:([a-zA-Z0-9][-]{0,1}){0,98}[a-zA-Z0-9])?$
It works for almost every cases. Except those 2 cases :
0-1234
(dash on the second character)Can someone help me please ? Thanks a lot !
Upvotes: 0
Views: 310
Reputation: 19375
Here's just an alternative to Jan's already perfect solution.
^(?:[^\W_]|(?<=[^\W_])-(?=[^\W_])){1,100}$
It can be "decrypted" as: between 1 and 100 occurrences of either
Upvotes: 1
Reputation: 43169
You are looking for lookaheads and another character class:
^(?!-)(?!.*-$)(?!.*--)[a-zA-Z0-9-]{1,100}$
Upvotes: 2