Reputation: 173
I have this information:
/([0123][0-9])-(\1)-(\d{4})/g
My question. Why the 'back reference' doesn't work? I'd like to understand what the syntax does and where i did make the mistake. Because in my understanding the first group ([0123][0-9])
should consider both numbers '10' and '16', or not? why?
Upvotes: 1
Views: 75
Reputation: 627609
A backreference only matches the same text that was captured with the corresponding capturing group. It does not repeat the pattern, but the already captured value.
In your case, \1
tries to match 16
after the first -
.
In JS regex, you can't use (?1)
/ \g<1>
subroutine calls that can be used in PCRE/Onigmo, but you may define the subpattern as a variable and build the pattern dynamically:
var target = "16-10-2017";
var p1 = "[0123][0-9]";
var rx = new RegExp("(" + p1 + ")-(" + p1 + ")-(\\d{4})", "g");
console.log(target.replace(rx, "$1/$2/$3"));
Upvotes: 3
Reputation: 60046
Maybe you have to change your regex to this (([0123][0-9])-){2}(\d{4})
, which mean that it should match two part of numbers
of two parts [0123]
and [a-9]
followed by -
(([0123][0-9])-){2}
Upvotes: 2