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

Viewed 602

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:

  • 4foo (start with a number)
  • foo bar (contains a space)
  • foo$@bar (contains special character)

Valid:

  • foo
  • foo_bar
  • Foo_Bar

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.

2 Answers

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

Try this out:-

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

Related