Trong Nguyen
Trong Nguyen

Reputation: 398

Regex for containing only alphanumeric characters and underscores, start with an alphabetic character

I'm trying to validate Firebase event name:

Event names can be up to 40 characters long, may only contain alphanumeric characters and underscores ("_"), and must start with an alphabetic character.

Invalid:

Valid:

I have tried \d?[^A-Za-z0-9_]+ which matches if there are any special characters and whitespace, but it won't match string with a digit character at the beginning.

Upvotes: 3

Views: 1565

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18641

Use

^[A-Za-z][A-Za-z0-9_]{0,39}$

See regex proof.

Synonyms:

^[A-Za-z]\w{0,39}$
^\p{L}\w{0,39}$
^[[:alpha:]]\w{0,39}$

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [A-Za-z]                 any character of: 'A' to 'Z', 'a' to 'z'
--------------------------------------------------------------------------------
  [A-Za-z0-9_]{0,39}       any character of: 'A' to 'Z', 'a' to 'z',
                           '0' to '9', '_' (between 0 and 39 times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

Upvotes: 2

RK_15
RK_15

Reputation: 939

Try this out:-

regex --> /^(?=[a-z].{39}$)(?=\w+$).+$/i

Upvotes: 0

Related Questions