What is the regular expression for the first character - is this a letter?

What is a regular expression, so that the first character is always a letter, and the rest can be letters or numbers or nothing at all?

I have this one that works when you enter at least two characters, but it doesn't work when you enter only one letter and nothing more.

/^[Az][A-z0-9]+$/ 

What do I need to change so that it allows only one letter? thanks

+5
source share
5 answers

Your regex is wrong:

 /^[Az][A-z0-9]+$/ 

You need to use:

 /^[A-Za-z][A-Za-z0-9]*$/ 

Since the range [Az] consists of non-alpha characters, just like [ , ] , ^ , etc. (basically something from 91-96 ASCII code).

It is also better to change the quantifier + to * , since your input can contain only one character.

+9
source

Your regex requires two characters (not the same as btw), because you are looking for one character, which is a letter, and at least one ( + ) letter or number.

To better get a line starting with a letter, then you need any other character:

 ^[A-Za-z].*$ 

^ means start of line

[A-Za-z] receives only letters, upper or lower

.* gets literally any character, 0 or more times

$ denotes the end of a line

+5
source

Replace modifier + with * (changing the value from "1 or more" to "0 or more").

+4
source

Change the regex to:

 /^[A-Za-z][A-Za-z0-9]*$/ ---------------------^ 

Be sure to change the value of + to * so that it matches 0 or more.

+2
source

You can do this:

  # ^(?i)[az][a-z0-9]*$ ^ # BOS (?i) # Ignore case [az] # az case insensitive [a-z0-9]* # Same as [^\W_] $ # EOS 
+1
source

Source: https://habr.com/ru/post/1200039/


All Articles