Tell us what’s happening:
Hi everyone
Another regex question: Trying to understand why the suggested solution (ie the freeCodeCamp solution) works and mine doesn’t. As I understand it, they BOTH should either fail or pass. I’d like to understand:
- Why my regex isn’t sufficient.
- Why the official solution works when it seems like it shouldn’t.
The task is to match exactly ‘42 42 42’ and reject ‘42 42 42 42’
This is my regex:
/(\d+)(\s)\1\2\1/; [fails]
And this is the official regex (slightly modified but still works):
/^(\d+)(\s)\1\2\1$/; [passes]
The only difference between the two seems to be the assertions of the start and the end of the string - but why does that matter?
The phrases ‘42 42 42 42’ and ‘42 42 42’ both start with a number and end with one. What does that have to do with the number of repetitions? It seems totally irrelevant.
Obviously, these assertions (^ and $) somehow affect how JavaScript counts the pattern, but I fail to see why. The explanations on the page doesn’t mention this at all. It would seem like /(\d+)(\s)\1\2\1/ should be interpreted as:
(\d+) → first digit pattern (first repetition)
(\s) → whitespace pattern (first repetition)
\1 → repeated pattern 1 once (second repetition)
\2 → repeat pattern 2 once (second repetition)
\1 → repeated pattern 1 again (third repetition)
And therefore pass the test.
What am I missing?
Thanks!
Your code so far
let repeatNum = "42 42 42";
let reRegex = /(\d+)(\s)\1\2\1/;
let result = reRegex.test(repeatNum);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0
Challenge: Regular Expressions - Reuse Patterns Using Capture Groups
Link to the challenge: