Expression Regular - Back References

DNick

I have this information:

  • target = 16-10-2017
  • pattern = /([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?

Regex Example Online

Wiktor Stribiżew

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related