Skip to content
Advertisement

How to write regex to match equal pairs of delimiters?

I have different dates like this:

DD-MM-YY
DD.MM.YYYY
YYYY/MM/DD

But the delimiter in the dates could be a dash - or a dot . or forward slash /.

I have tried regex that works but I need to check if date is entered with non-matching delimiters like this DD-MM/YY then it should be invalid because the 1st delimiter is - and 2nd one is /.

My attempt so far:

/^dd?d?d?[-/.]d?d[-/.]dd?d?d?$/.test(userDate)

How can I check if the 2nd delimiter is same as 1st delimiter?

Advertisement

Answer

Working example using d to capture digits, ([-/.]) to capture the first delimiter, and a regex backreference 1 to re-capture the same delimiter as in the first capture group:

function testUserDate(userDate) {
  let regex = /^d{1,4}([-/.])d{1,2}1d{1,4}$/;
  return regex.test(userDate);
}

console.log(testUserDate("2007-11-12")); // true
console.log(testUserDate("2007.11.12")); // true
console.log(testUserDate("2007/11/12")); // true
console.log(testUserDate("2007/11-12")); // false
console.log(testUserDate("2007.11/12")); // false
console.log(testUserDate("12-12-2007")); // true
console.log(testUserDate("12/12/2007")); // true
console.log(testUserDate("12.12.2007")); // true
console.log(testUserDate("12/12-2007")); // false
console.log(testUserDate("12-12.2007")); // false
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement