Search code examples
javascriptregexreplacecapturing-group

Why doesn't this RegExp work as expected?


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


Solution

  • 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