Reputation: 5348
Using RegEx to validate user input, I would like to match any string that starts with a letter, followed by 0 or more characters like so:
\A[a-z][a-z0-9_-]*
but which forbids hyphens and underscores as the last character in the string. How do I finish this RegEx?
Examples of matching strings:
a
a-b
ab_c--de
Examples of non-matching strings:
a-
abc-
a_
-
Upvotes: 1
Views: 268
Reputation: 10865
I'm not sure it needs lookahead/behind. Does this work for you?
\A[a-z]([-_]*[a-z0-9])*\Z
Upvotes: 3
Reputation: 67968
^(?!.*(?:_|-)$)[a-z][a-z0-9_-]*$
This should do it for you.See demo.
https://regex101.com/r/uE3cC4/33
Upvotes: 2