bootsa
bootsa

Reputation: 249

js regex - allow letters, number and a dash, but not one dash or more on its own

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

Answers (2)

bobble bubble
bobble bubble

Reputation: 18555

By use of a word boundary:

/^-*\b[a-z\d-]*$/i

demo at regex101


Or requiring one letter/digit:

/^-*[a-z\d][a-z\d-]*$/i

demo at regex101


Or use of a negative lookahead to prevent matching strings only consisting of dashes:

/^(?!-+$)[a-z\d-]+$/i

demo at regex101

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

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

Related Questions