Giuseppe
Giuseppe

Reputation: 5348

A regex that forbids certain characters at the end of a string

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

Answers (3)

dawg
dawg

Reputation: 103884

You can do:

\A([a-z][a-z\d_-]*[a-z\d]|[a-z])\Z

Demo

Upvotes: 1

jas
jas

Reputation: 10865

I'm not sure it needs lookahead/behind. Does this work for you?

\A[a-z]([-_]*[a-z0-9])*\Z

Upvotes: 3

vks
vks

Reputation: 67968

^(?!.*(?:_|-)$)[a-z][a-z0-9_-]*$

This should do it for you.See demo.

https://regex101.com/r/uE3cC4/33

Upvotes: 2

Related Questions