简体   繁体   中英

regex to allow 1 to 4 alphabet at starting of string and then followed by any number of digits

I am trying to validate a field which can take input as following ways:

  1. should take 1 to 4 alpha charcters.(but should start with alpha)
  2. from 5th position to so on should take numbers.(no where from 5th should accept alphabets)
  3. in between 1-4 characters of alpha it should not allow numbers. 4.even if first 4 characters are entered it should accept.(that 4 characters should be alpha.ex:"asdf") ^[a-zA-Z][0-9]$

i have many things and searched many sites.i could not find it.please help me. Thank you in advance.

For an answer off the top of my head:

^[a-zA-Z]{1,4}[0-9]+$

will match a string with the following break down:

  1. ^ = Start of string
  2. [a-zA-Z] = a through z (case-insensitive)
  3. {1,4} = 1 to 4 times
  4. [0-9]+ = one or more numbers
  5. $ = End of string

Because each situation is different, I would suggest using an online regex tester to test certain strings of characters.

^[a-zA-Z]{1,4}\d*
  • [a-zA-Z] is for alpha chars
  • `\\d' is short for numbers
  • {1,4} specify 1 to 4 chars
  • * specify any number of digits (including none)

Try this:

^[A-Za-z]{1,4}\d*$

https://regex101.com/r/yH6pR3/1

It will only allow 1-4 alpha characters, and then only digits thereafter. Digits are optional. You can change that by making it \\d+ instead.

I am wondering what you mean by digits only from 5th position onward. What if there are three or less alpha at the start of the string?

UPDATE:

^(?:[A-Za-z]{1,4}|[A-Za-z]{4}\d+)$

https://regex101.com/r/qQ8nR2/1

First it attempts to match just 1-4 characters. If that fails, then it attempts to match 4 characters followed by 1 or more digits.

You can also write it this way:

^\p{L}{1,4}\d+$

\\p{L}{1,4} matches any letter 1 to 4 times

\\d+ matches any digit one or more times

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM