1

I want a regular expression to allow first character be an alphabet and then numbers only with following constraints :

-no space

-no special characters

like AS2, Nf2, nf_2, nf 08 should not be allowed. 'N00044,n0,n09,n099,123456,123' allowed

Community
  • 1
  • 1

2 Answers2

2

You can try this regex :

^[A-z]\d+$ 

if you want a minimum of 1 digit necessary, or

^[A-z]\d*$

if having a digit is not mandatory.

Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • Depending on the flavor of regex, your query might not match both lowercase and uppercase characters in the first position. – Tim Biegeleisen Feb 08 '17 at 06:29
  • Yes, I purposely mentioned that regex since alphanumeric include both uppercase as well as lowercase letters. @TimBiegeleisen – Jarvis Feb 08 '17 at 06:31
  • 2
    Nice trick, didn't know that `[A-z]` covers both upper and lower case +1 – Tim Biegeleisen Feb 08 '17 at 06:33
  • For those who might be interested, `[a-Z]` won't work because `Z` comes before `a` in the character sequence. – Tim Biegeleisen Feb 08 '17 at 06:36
  • @Jarvis above is correct could you tell me check above or all numeric characters 'N00044' or '123456' is correct –  Feb 08 '17 at 06:50
  • Can you elaborate ? I don't understand what you are asking. @AkhilJain – Jarvis Feb 08 '17 at 06:51
  • @Jarvis check above or all numeric characters i.e 'N00044' or '123456' is correct (adding numeric char) either the above works or all numeric condition –  Feb 08 '17 at 06:54
2

Jarvis's does meet the requirement but you can also use numeric range for the same since \d is specifically used for ASCII numbers. Refer when to use \d and [0-9].

Since numbers are required to be matched in your regex I would prefer as follows:

 ^([A-z][0-9]+)$

Regex101- test cases

As per your requirement in comments, following regex should do the work for you:

^(([A-z][0-9]+)|([0-9]+))$

Regex101- New test cases

It will match an input with alphabet followed by numbers or an input with only numbers.

Community
  • 1
  • 1
Dhaval Simaria
  • 1,886
  • 3
  • 28
  • 36