-1

I made a RegExp to format an incoming date string, but it doesn't work as expected with my usage. I was hoping someone could explain why not:

var data = [
  "m_2013_01_01",
  "m_2013_02_01",
  "m_2013_03_01",
  "m_2013_04_01"
];

// why aren't these equivalent?
//  expected
console.log(data.map(datum => datum.replace(/^m_(\d+)_(\d+)_(\d+)/g, '$1-$2-$3')));
//  ???
console.log(data.map(datum => datum.replace(/^m_(?:(\d+)_?){3}$/g, '$1-$2-$3')));
Patrick Roberts
  • 40,065
  • 5
  • 74
  • 116
  • 1
    You should never use quantifiers on capturing groups, if you actually want to use them in any way, as only the last occurence of this group is actually stored. – Sebastian Proske Jul 08 '16 at 21:22

1 Answers1

5

In the fist regex you are using 3 groups:

Regular expression visualization

That's why you can reference group 1, 2 and 3.

However, in the second regex you are using 1 group repeated multiple time, so group 2 and 3 doesn't exist and can't be referenced:

Regular expression visualization

Federico Piazza
  • 27,409
  • 11
  • 74
  • 107