Reuse Patterns Using Capture Groups - Issue

Hi everyone,

I’m having a tough time understanding why the following code (which I got from trial and error) is passing:

let reRegex = /^(\d+)(\s)\1\2\1$/;

From my understanding that Regex would work for anything in the following pattern:

"[word](space)[word]"

And it would have to be explicitly that pattern because of the ^ at the beginning and the $ at the end.

However its passing 3 words with two spaces in between.
e.g.

“42 42 42”
"100 100 100

But not (as its 4 numbers)

“42 42 42 42”

Can anyone explain why this pattern seems to pass?

Thanks!

You regex is parsed in the following way:

^      : From start of the line
(\d+)  : Match group (1st) of one or more digits
(\s)   : Followed by a group (2nd) of whitespace character
\1     : Followed by whatever was captured in the first group
\2     : Followed by whatever was captured in the second group
\1     : Followed by whatever was captured in the first group
$      : Followed by the end of line
1 Like

Ohhh I see

I didn’t realise the initial capture group declarations counted in addition to the backslash /1 & /2.

Thanks for your help!