简体   繁体   中英

Regex for first two character of string alphabet and last two should be numeric

I want to validate a string like

1.AB97CD11

Cases

  1. Total length of string min=4, max=8
  2. First two characters must be alphabetic
  3. Last two characters must be numeric.

I tried this Regex, but it does not work for me:

^[a-zA-Z]{2}[a-zA-Z0-9]{4}[0-9]{2}$

Try the following pattern:

^[A-Z]{2}[A-Z0-9]{0,4}[0-9]{2}$

The {0,4} width delimiter on the middle characters ensures that the total length must be between 4 and 8 characters. I am assuming that you only expect uppercase letters. If the letters could also be lowercase, then use [A-Za-z] instead of [az] .

So I guess you want all 3 conditions to be met at the same time.

You want to use quantifiers to specify the number of letters / digits.

[a-zA-Z]{2}[\\w]{0,4}[0-9]{2}

would do the job.

Explanation taken from https://regex101.com/

Match a single character present in the list below [a-zA-Z]{2}
{2} Quantifier — Matches exactly 2 times
a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
Match a single character present in the list below [\w]{0,4}
{0,4} Quantifier — Matches between 0 and 4 times, as many times as possible, giving back as needed (greedy)
\w matches any word character (equal to [a-zA-Z0-9_])
Match a single character present in the list below [0-9]{2}
{2} Quantifier — Matches exactly 2 times
0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)

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