Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 874
Prashobh Avatar asked Nov 28 '22 13:11

Prashobh


1 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*)?$
 ^^^           ^^
like image 89
Wiktor Stribiżew Avatar answered Jan 19 '23 00:01

Wiktor Stribiżew