简体   繁体   English

正则表达式:匹配两个条件之一?

[英]Regular expression : match either of two conditions?

Hi I don't know much about regular expression. 嗨,我对正则表达式了解不多。 But I need it in form validation using angularJs. 但是我需要使用angularJs进行表单验证。

Below is the requirement 以下是要求

The input box should accept only if either 输入框应仅接受以下任一情况

(1) first 2 letters alpha + 6 numeric (1)前2个字母的字母+ 6个数字

or 要么

(2) 8 numeric (2)8个数字

Below are some correct Inputs :- 以下是一些正确的输入:-

(1)SH123456 (2)12345678 (3)sd456565 (1)SH123456(2)12345678(3)SD456565

I tried data-ng-pattern="/(^([a-zA-Z]){2}([0-9]){6})|([0-9]*)?$/" , Its working fine for both the above condition but still it is accepting strings like S2D3E4F5 and may be many other combination as well. 我尝试了data-ng-pattern="/(^([a-zA-Z]){2}([0-9]){6})|([0-9]*)?$/" ,它的对于上述两种情况都可以正常工作,但仍可以接受S2D3E4F5之类的字符串,并且可能还有许多其他组合。

What I am doing wrong I am not able to find it out. 我做错了我无法找到答案。

Any help is appreciable !!! 任何帮助都是可观的!

Thanks 谢谢

In your regex, the two alternative branches are anchored separately: 在您的正则表达式中,两个替代分支分别锚定:

  • (^([a-zA-Z]){2}([0-9]){6}) - 2 letters and 6 digits at the start of the string (^([a-zA-Z]){2}([0-9]){6}) -字符串开头的2个字母和6个数字
  • | - or - 要么
  • ([0-9]*)?$ - optional zero or more digits at the end of the string ([0-9]*)?$ -字符串末尾的可选零个或多个数字

You need to adjust the boundaries of the group: 您需要调整组的边界:

data-ng-pattern="/^([a-zA-Z]{2}[0-9]{6}|[0-9]{8})?$/"
                   ^                         ^^^^ 

See the regex demo . 参见regex演示

Now, the pattern will match: 现在,模式将匹配:

  • ^ - start of string ^ -字符串开头
  • ( - start of the grouping: ( -分组开始:
    • [a-zA-Z]{2}[0-9]{6} - 2 letters and 6 digits [a-zA-Z]{2}[0-9]{6} -2个字母和6位数字
    • | - or - 要么
    • [0-9]{8} - 8 digits [0-9]{8} -8位数字
  • )? - end of the grouping and ? -分组结束? quantifier makes it match 1 or 0 times (optional) 量词使其匹配1或0次(可选)
  • $ - end of string. $ -字符串结尾。

You can try this DEMO LINK HERE 您可以在此处尝试此演示链接

^(([a-zA-Z]{2}|[0-9]{2})[0-9]{6})?$

It will accept: 它将接受:

  1. ab123456 AB123456
  2. 12345678 12345678
  3. aa441236 aa441236
  4. aw222222 aw222222

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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