dafunk
dafunk

Reputation: 111

Matching strings with underscores, lowercase ASCII letters, ASCII digits, hyphens or dots only not starting with dot and hyphen

I need regular expression which could match a string like that

_test
123test
test
test_123
test-123
123.a

I created this regular expression:

/^[_0-9a-z][_.\-a-z0-9]*$/

However, I want to exclude a string if it only contains numbers.

How can I fix it?

Upvotes: 2

Views: 98

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

To avoid matching a digit-only string, add a negative lookahead:

^(?![0-9]+$)[_0-9a-z][_.\-a-z0-9]*$
 ^^^^^^^^^^

The (?![0-9]+$) lookahead is triggered only once at the beginning of the string and will try to match one or more digits up to the end of string. If they are found, a match will be failed (no match will be returned) as the lookahead is negative.

Upvotes: 3

Related Questions