0

I was working with an exercise on FCC and got confused by RegEx's capture group behaviors. I would appreciate if an expert could help me clear my confusion. Why did not fixRegex2 works?

let str = "one two three";
let fixRegex = /(\w+)\s(\w+)\s(\w+)/; 
let fixRegex2 = /(\w+)(\s)\1\2\1/; 
console.log(str.match(fixRegex));//works ok, return "one two three"
console.log(str.match(fixRegex2));//no match at all!

I am pretty sure fixRegex2 would work since I did something similar in the past and it worked:

let repeatNum = "42 42 42";
let reRegex = /(\d+)(\s)\1\2\1/;
console.log(repeatNum.match(reRegex));// works ok, return "42 42 42"
  • 2
    `\1` is a backreference to the text that was matched by group 1 (in your case the word `one`), **not** the regex inside group 1 (`\w+`). It works in your other example because the text captured by group 1 (`42`) is repeated in the string. – Nick Mar 25 '20 at 03:55
  • Nick: Thanks for your comment. Took me 15 minutes to think about this but I think I get it now ^.^ – user3608384 Mar 25 '20 at 07:11
  • No worries - I'm glad it was helpful. – Nick Mar 25 '20 at 07:13

0 Answers0