Do not understand :Reuse Patterns Using Capture Groups

hey guys,

i really love the java course, but now im relly stuck.
i dont relly get the system at this topic.

Can someon explain how these “\1” works exactly?

my understanding is:

Hint1:


let testString = "test test test";
let reRegex = /(test)\s\1/;
let result = reRegex.test(testString);

\1 stands for first match “test whitespace” so result should be 3x "test " because there are 3 tests…
But result is “test test”
So does it mean: how many time is there pos 1 (test) in the rest of the string?

Hint 2:


let testString = "test test test";
let reRegex = /(test)(\s)\1\2\1/;
let result = reRegex.test(testString);

For above with my “explanation” that means:

\1 -> result “test test” but its wrong…
\2 -> is for? \s??? makes no sense, so everything 2 times is more less sense
and the last \1 is for what?

I dont really get it…

thanks for help…

Your code so far


let repeatNum = "42 42 42";
let reRegex = /(\d{1,})(\s)\1\2/; // Change this line
let result = reRegex.test(repeatNum);
console.log (result)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

Challenge: Reuse Patterns Using Capture Groups

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups

1 Like

Hey seyo,

the use case to replace (\s) with \2 might look complicated in this situation but think about more complex pattern groups that you want to repeat in a regular expression. Then it makes sense to group one part and only repeat it with something like “\1” or how many groups you have.

The number (i.e. \1, \2) depends on how many groups you created in your regex.
Example:
/(test)\s\1/ => only “\1” would be available and the regex could also be written as /test\stest/

Another example:
/(test)(\s)\1\2\1/ => “\1” and “\2” is available as you grouped to parts in regex with “()” and it could also be rewritten as /test\stest\stest/

I hope this helps a little bit to understand it better.

Thanks and best regards,
ewatch

ahhh okay, so every \number is equal to every () group in order, so if i would have an pattern like:

(hallo)(this)(is)(a)(test)
is equal to:
1\2\3\4\5

so the regex = \2\4\1\5 would be something like: this a hallo test?

Yes you are totally right. :+1: