Fedorov Dmitriy
Fedorov Dmitriy

Reputation: 19

REGEX from PHP to JS

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

Upvotes: 0

Views: 437

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

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"));

Upvotes: 1

Related Questions