How to combine 3 regular expressions?

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})$/
+3
source share
3 answers
/^(\d{1,2})([\/.-])(\d{1,2})\2(\d{2})$/

Beware, there is now a new capture 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., you can use

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

The easiest way is to write:

(r1)|(r2)|(r3)

where ri are the regular expressions you have. You can separate the common parts, of course, like anchors, therefore

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

In fact, in your case, regular expressions differ only in the separator characters used, so you can put them in a character class to get a common regular expression.

+2
source

:

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

All Articles