Regular Expressions - Reuse Patterns Using Capture Groups

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:

  1. Why my regex isn’t sufficient.
  2. 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?


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:

let repeatNum = “42 42 42”;
let reRegex = /(\d+)(\s)\1\2\1/;
let result = reRegex.test(repeatNum);

This will test true. So will all the following:

repeatNum = "42 42 42 42"; 
repeatNum = "42 42 42   "; 
repeatNum = "42 42 42  x";

The caret (^) indicates that a match must occur at the beginning of the searched text. And the dollar ($) for a match at the end of the searched text.

Without these two “limiters”, your regex pattern /(\d+)(\s)\1\2\1/ can include any other text in addition to the matching string.

Another example for your regex:

'ábcd 123 xyz 1 1 1 z' will match - the matching part is the '1 1 1', that is the pattern your regex matches.
'ábcd 123 xyz 1 1 z' will not match - there is no pattern match for your regex.

Note that regular expression specifies a search pattern in text.

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