问题描述
我对正则表达式了解不多.但是我需要使用angularJs进行表单验证.
Hi I don't know much about regular expression. But I need it in form validation using angularJs.
以下是要求
输入框应仅在以下任一情况下接受
The input box should accept only if either
(1)前2个字母的字母+ 6个数字
或
(2)8位数字
下面是一些正确的输入:-
Below are some correct Inputs :-
(1)SH123456(2)12345678(3)sd456565
(1)SH123456(2)12345678(3)sd456565
我尝试了 data-ng-pattern ="/(^([a-zA-Z]){2}([0-9]){6})|([0-9] *)?$/"
,在上述条件下都可以正常工作,但仍可以接受S2D3E4F5之类的字符串,并且可能还有许多其他组合.
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.
我做错了什么,我找不到它.
What I am doing wrong I am not able to find it out.
任何帮助都是有意义的!
Any help is appreciable !!!
谢谢
推荐答案
在您的正则表达式中,两个替代分支分别锚定:
In your regex, the two alternative branches are anchored separately:
-
(^([a-zA-Z]){2}([0-9]){6})
-字符串开头的2个字母和6个数字 -
|
-或 -
([0-9] *)?$
-字符串末尾的可选零个或多个数字
(^([a-zA-Z]){2}([0-9]){6})
- 2 letters and 6 digits at the start of the string|
- or([0-9]*)?$
- optional zero or more digits at the end of the string
您需要调整组的边界:
data-ng-pattern="/^([a-zA-Z]{2}[0-9]{6}|[0-9]{8})?$/"
^ ^^^^
请参见 regex演示.
现在,模式将匹配:
-
^
-字符串的开头 -
(
-分组开始:-
[a-zA-Z] {2} [0-9] {6}
-2个字母和6个数字 -
|
-或 -
[0-9] {8}
-8位数字
^
- start of string(
- start of the grouping:[a-zA-Z]{2}[0-9]{6}
- 2 letters and 6 digits|
- or[0-9]{8}
- 8 digits
这篇关于正则表达式:匹配两个条件之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
-