字符串字母的前两个字符的正则表达式,后两个应为数字

时间:2019-07-03 13:02:50

标签: javascript php jquery html

我想验证

之类的字符串
1.AB97CD11

情况

  1. 字符串的总长度min = 4,max = 8
  2. 前两个字符必须为字母
  3. 最后两个字符必须是数字。

我尝试过此正则表达式,但对我不起作用:

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

2 个答案:

答案 0 :(得分:0)

尝试以下模式:

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

中间的字符{0,4}的宽度定界符确保总长度必须在4到8个字符之间。我假设您只期望大写字母。如果字母也可以是小写字母,请使用[A-Za-z]代替[a-z]

答案 1 :(得分:0)

所以我想您希望同时满足所有三个条件。

您要使用量词来指定字母/数字的数量。

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

会做这份工作。

说明取自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)