0

Could you suggest how to correct this expression

(^([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))(?:,\s*(?1))*$)

for use with javascript, so that it gives the true when the date formats are yyyy-mm-yy and when the dates are listed separated by commas if there are several of them?

Expected result:
2017-03-25, 2017-03-27, 2017-03-28 true
2017-03-25 true
4
  • 1
    Maybe like so: ^(([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])(,\s)?)+)$ Commented Feb 18, 2020 at 7:19
  • JavaScript doesn't support recursive regexp. You should do it using a quantifier instead. Commented Feb 18, 2020 at 7:25
  • This doesn't work as it should, result 2017-03-25, 2017-03-27, 2017-03-28 false ( must be true) 2017-03-25 true Commented Feb 18, 2020 at 7:27
  • (?1) stands for the whole Group 1 pattern. So, the right answer is ^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])(?:,\s*[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))*$, regex101.com/r/FomX9Q/1. Actually, your PHP regex has a bug. Commented Feb 18, 2020 at 8:27

1 Answer 1

1

Your PHP regex contains a bug, namely, the Group 1 parentheses are wrapping the whole pattern while the recursed part should only be ([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]).

So, in order to fix the PHP pattern, you need to remove the outer parentheses:

^([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))(?:,\s*(?1))*$

Since the (?1) regex subroutine recurses the Group 1 pattern, all you need is to repeat the pattrn in a JS regex:

^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])(?:,\s*[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))*$

See this regex demo.

In JS code, do not write it as a regex literal, create it dynamically for easier maintenance:

const date_reg = `[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])`;
const reg = new RegExp(String.raw`^${date_reg}(?:,\s*${date_reg})*$`);
console.log(reg.test("2017-03-25, 2017-03-27, 2017-03-28"));

Sign up to request clarification or add additional context in comments.

1 Comment

@FedorovDmitriy I also linked the answer to another one that is also related to PHP to JS regex conversion, just in case someone stumbles across a related problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.