Something unclear with the regex again, please give us a hand

this is the challenge link the challenge

this is the example given as an explanation to the lesson:

let repeatStr = "row row row your boat";
let repeatRegex = /(\w+) \1 \1/;
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns ["row row row", "row"]

the question is after I understood that I can access the substring matched by using the number of the capture group that matched it, in this case, it’s \1. why in the regex of the example they used two \1s: /(\w+) \1 \1/ ?(this interrogation mark is for my question, not part of the regex I’m stating).
thank you.

`let repeatNum = "42 42 42";
let reRegex = /(\d+)(\s)\1\2\1/; // my solution
let result = reRegex.test(repeatNum);
let res = repeatNum.match(reRegex);

and the hint page solution:

let reRegex = /^(\d+)\s\1\s\1$/; // this has passed the challenge

how in their solution they could use caret and dollar signs in the same regex? matching beginning and end of the string , and why?

the link to challenge

You can use both ^ and $. In fact, you often do. If you want to make sure that there is nothing else before your pattern and nothing else after your pattern, then you need to specify the beginning and end of the string.

1 Like

Hi! I do have a doubt and I hope you can help me:

let repeatStr = “row row row your boat”;

let repeatRegex = /(\w+) \1 \1/; // they refer to the substring twice

repeatStr.match(repeatRegex); // Returns [“row row row”, “row”]
//So over here shouldn’t that return [“row row row”, “row”, “row”]

So what is it that I´m missing

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.