Prashobh
Prashobh

Reputation: 9544

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

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.

Upvotes: 5

Views: 13442

Answers (4)

Caius Jard
Caius Jard

Reputation: 74710

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..

Upvotes: 3

marvel308
marvel308

Reputation: 10458

you can use the regex

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

see the regex101 demo

Upvotes: 6

anubhava
anubhava

Reputation: 786091

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.

Upvotes: 5

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627488

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*)?$
 ^^^           ^^

Upvotes: 13

Related Questions