HappyCoding HappyCoding - 4 months ago 11
Javascript Question

Specific match with "OR condition" - regex

I'm making a regex to match

datetime
with these formats:

d/M/yyyy
d-M-yyyy
M/d/yyyy
M-d-yyyy
dd/MM/yyyy
dd-MM-yyyy
MM/dd/yyyy
MM-dd-yyyy
...


I've tried:



var reg = /^(\d{1,4}[/\-]\d{1,2}[/\-]\d{1,4}\s(\d{1,2}:){2}\d{1,2})$/;
alert(reg.test('18/07/2016 00:00:00'));





It works fine. But the problem is: it still works with this format:

d/M-yyyy

//or

dd-MM/yyyy


I saw the index of the problem is in
[/\-]
. I need it's duplicate correct
/
OR
-
(only one).

My question: how can I fix it?

Answer

Use a capturing group:

^\d{1,4}([/-])\d{1,2}\1\d{1,4}\s(\d{1,2}:){2}\d{1,2}$

\1 will match the same text as what matched the 1st capturing group, which is is ([/-]).