Soham Dasgupta
Soham Dasgupta

Reputation: 5199

Regex to match string containing letters and only underscore

Well my question is simple, I want to match a string with following attributes

Please help in creating such a regex.

Upvotes: 3

Views: 9820

Answers (2)

RolandasR
RolandasR

Reputation: 3047

/^[a-zA-Z]\w*$/

a-Z - start with letter

\w - all leters, numbers and underscore

Upvotes: 1

Joey
Joey

Reputation: 354566

^[a-zA-Z][a-zA-Z0-9_]*$

Dissecting it:

  • ^ start of line/string
  • [a-zA-Z] starts with a letter
  • [a-zA-Z0-9_]* followed by zero or more letters, underscores or digits.
  • $ end of line/string

If you need to consider Unicode, then the following is probably more sane:

^\p{L}[\p{L}\p{Nd}_]*$

This will match not only ASCII letters and digits but across all scripts that are supported by Unicode. Digits are restricted to decimal digits, only, so you won't get Roman numerals.

Upvotes: 10

Related Questions