开发者

How to union 3 regular expression?

M/D/YY    /^(\d{1,2})\/(\d{1,2})\/(\d{2})$/           
M-D-YY    /^(\d{1,2})\-(\d{1,2})\-(\d{2})$/
M.D.YY    /^(开发者_开发百科\d{1,2})\.(\d{1,2})\.(\d{2})$/


/^(\d{1,2})([\/.-])(\d{1,2})\2(\d{2})$/

Watch out, now there is a new capturing group, so the year will be in backreference number 4 instead of 3 as before.

If you also want to allow M/D-YY etc., then you can use

/^(\d{1,2})[\/.-](\d{1,2})[\/.-](\d{2})$/


The simplest way is to write:

(r1)|(r2)|(r3)

where the ri are the regular expressions you have. You can factor out common parts, of course, like the anchors, so

^(?:(r1)|(r2)|(r3))$

In fact, in your case the regexes differ only in the separator characters used, so you could put them in a character class to get a common regex.


You need to capture the first separator and do a back-reference:

/^(\d{1,2})([\/-\.])(\d{1,2})\2(\d{2})$/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜