user1926319
user1926319

Reputation: 33

Regex for name should start with a letter

I am trying to write a regex for name which starts with a letter and can also have spaces, numbers in the string.

Currently I am using ^(?=.*[a-zA-Z].*)([a-zA-Z0-9' ]{1,50})$.

But it is accepting the string like "1125151asdgvhavdg". i.e., it is taking numbers at the starting.

My string should look like this

ads564564545456 fdsf78

Upvotes: 1

Views: 768

Answers (4)

stema
stema

Reputation: 92976

If you are not 100% sure that there will be forever only Ascii letters to be matched, then you should have a look at Unicode properties, e.g. for letter \p{L}.

\p{L} any kind of letter from any language.

Or Unicode scripts, that collect letters needed for certain languages.

So your regex would look like this:

^\p{L}[\p{L}\p{Nd}' ]{0,49}$

I replaced also 0-9 by the property \p{Nd} (a digit zero through nine in any script except ideographic scripts.)

Upvotes: 0

Bohemian
Bohemian

Reputation: 425003

You can express it succinctly like this:

 ^(?i)[a-z][a-z\d ]{0,49})$

Upvotes: 0

mck
mck

Reputation: 988

You can use following code:

^([a-zA-Z\s][a-zA-Z0-9]{1,50})$

This regex starts with characters and allow spaces and numbers.

Upvotes: 0

zerkms
zerkms

Reputation: 254916

As simple as:

^([a-zA-Z][a-zA-Z0-9' ]{0,49})$

You don't need any assertions here

Upvotes: 5

Related Questions