axnet
axnet

Reputation: 5780

how to build validation regex with starting and ending character validations?

how to build explicit Regex for string with alphabet at start and underscore or digit in the middle and alphabet or digit at end?

the pattern tried so far can be seen here with test cases. https://regex101.com/r/JedpJu/3

I want to filter out strings like following.

_ (only underscore)

9a_d (string starting with numbers)

ad_ (ending with underscores)

EDIT

ad*d_rr (any special character apart from underscore also should not be allowed.)

Upvotes: 1

Views: 179

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You may use

^[A-Za-z](?:[A-Za-z0-9_]*[A-Za-z0-9])?$

which is the same as

^[A-Za-z](?:\w*[A-Za-z0-9])?$

See the regex demo

In Java, you may use it with .matches() and omit the anchors:

s.matches("[A-Za-z](?:[A-Za-z0-9_]*[A-Za-z0-9])?")
s.matches("[A-Za-z](?:\\w*[A-Za-z0-9])?")

If the string may include line breaks use

s.matches("(?s)[A-Za-z](?:[A-Za-z0-9_]*[A-Za-z0-9])?")
s.matches("(?s)[A-Za-z](?:\\w*[A-Za-z0-9])?")

where (?s) enables . to match line break chars.

Upvotes: 1

Related Questions