Regular Expressions - Reuse Patterns Using Capture Groups - Confusion around the fourth 42

Tell us what’s happening:
I’ve read the solution post for this challenge, but I’m having trouble coming to grips with it.

Isn’t the regex by default a literal string comparison match? If that’s the case, and I’m not using /g at the end of the regex, why is the second \1 matching the fourth “42”?

According to the explanation I saw in the answer thread, the (\d+) matches the second 42?? I saw someone else ask the question in the answer thread, but no one answered. Why isn’t the code below an exact match for only 42 42 42 (or 100 100 100) and nothing else?

I’m sorry, I thought I had a decent grasp of this until this challenge, and now I’m thoroughly confused by what is going on. Thanks for the help!
Your code so far

let repeatNum = "42 42 42 42";
let reRegex = /(\d+) \1 \1/ ; // Change this line
let result = reRegex.test(repeatNum);

Your browser information:

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

Challenge: Regular Expressions - Reuse Patterns Using Capture Groups

Link to the challenge:

it is not matching the last 42. (it is matching the first 3 42’s and ignoring the last)
The output from your log is:

[ '42 42 42',
  index: 0,
  input: '42 42 42 42',
  groups: undefined ]

The first value of the array is the actual match.
The second is what the \1 evaluated to.
the index tells you that the matched string starts from index 0 in the input string

Thanks for the response.
So if that’s the case, why does the challenge fail because it’s matching 42 42 42 42?

because the js test function is returning true.
(and that’s what the fcc test cares about).

So you are meant to match 42 42 42 which you did but you didn’t exclude a match from occurring in a larger string 42 42 42 42

Oh. In my long-winded answer I was typing to you, I think I found understanding. Thanks hbar1st.

1 Like

To verbalize my understanding; I was going to write something along the lines of…
If I were testing “ahhhh” and my regex pattern were /h/, test would find the first “h” and stop there with a “true” result. Which is exactly the problem. I need it to fail, because of the excess "h"s at the end, so I would do something like (to make it relevant to the example) /^ah$/, which would cause ahhh to fail, but ah to pass.

1 Like