Reputation: 249
I want a regex that allows letters, number and a dash, which is ([a-z0-9\-]+)
, but I don't want one or more dashes on its own without a letter(s) or a number(s)
Is it possible?
--- Invalid
- Invalid
3e-qw Valid
-3- Valid
-a- Valid
Upvotes: 1
Views: 64
Reputation: 18555
By use of a word boundary:
/^-*\b[a-z\d-]*$/i
Or requiring one letter/digit:
/^-*[a-z\d][a-z\d-]*$/i
Or use of a negative lookahead to prevent matching strings only consisting of dashes:
/^(?!-+$)[a-z\d-]+$/i
Upvotes: 2
Reputation: 92894
Use the following pattern:
[a-zA-Z0-9-]*(?=[a-zA-Z0-9])[a-zA-Z0-9-]*
https://regex101.com/r/E1yHVY/17
Upvotes: 0