Regex for a string which do not start with a number and allow only alphanumeric

Viewed 9680

I am trying to create a javascript regex for below conditions

  • Allow Alphanumeric only
  • But also allow underscore(_)
  • Don't allow to start with a number
  • Don't allow to start with an underscore

I have created a regex ^(?![0-9]|[_].*$).* which will work for last two conditions above. Please suggest how can I add an and condition to make it work for all above scenarios.

4 Answers

You may use the following regex:

^[A-Za-z]\w*$

Details

  • ^ - start of string
  • [A-Za-z] - any ASCII letter
  • \w* - zero or more letters/digits/_
  • $ - end of string.

To allow an empty string match, wrap the whole pattern with an optional non-capturing group:

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

You can use this regex:

^(?![0-9_])\w+$

RegEx Demo

(?![0-9_]) is negative lookahead to fail the match when we have a digit or _ at the start.

you can use the regex

^[a-zA-Z][A-Za-z0-9_]*$

see the regex101 demo

You may be thinking too literally about the last two requirements. If it's alphanumeric (so.. a-z and 0-9, right?) then saying "dont allow numbers or underscore at the start" is probably the same as "must start with a letter"

^[a-z][a-z0-9_]*$

This is "must start with a-z", followed by "must follow with zero or more letters, numbers or underscores. The ^ outside of a character class (for example [a-z] is a character class) means "start of input". The $ means end of input.

If you interpreted the last two requirements literally, you could write:

[^0-9_] 

This means "any character that is not 0-9 and also not an underscore" but it doesn't necessarily restrict the user from entering something other than a-z as the first character, so they might enter a #, and it would pass..

Related