最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regular expression : match either of two conditions? - Stack Overflow

programmeradmin1浏览0评论

Hi I don't know much about regular expression. But I need it in form validation using angularJs.

Below is the requirement

The input box should accept only if either

(1) first 2 letters alpha + 6 numeric

or

(2) 8 numeric

Below are some correct Inputs :-

(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.

What I am doing wrong I am not able to find it out.

Any help is appreciable !!!

Thanks

Hi I don't know much about regular expression. But I need it in form validation using angularJs.

Below is the requirement

The input box should accept only if either

(1) first 2 letters alpha + 6 numeric

or

(2) 8 numeric

Below are some correct Inputs :-

(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.

What I am doing wrong I am not able to find it out.

Any help is appreciable !!!

Thanks

Share Improve this question asked Sep 21, 2016 at 9:49 shreyanshshreyansh 1,6875 gold badges30 silver badges49 bronze badges 2
  • Possible duplicate of In a regular expression, match one thing or another, or both – David R Commented Sep 21, 2016 at 9:51
  • @DavidR No, this is not a duplicate of that. It’s an anchoring problem. – tchrist Commented Sep 22, 2016 at 2:49
Add a comment  | 

2 Answers 2

Reset to default 8

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
  • | - or
  • ([0-9]*)?$ - optional zero or more digits at the end of the string

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.

Now, the pattern will match:

  • ^ - 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
  • )? - end of the grouping and ? quantifier makes it match 1 or 0 times (optional)
  • $ - 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
  2. 12345678
  3. aa441236
  4. aw222222
发布评论

评论列表(0)

  1. 暂无评论