Regular Expressions - Reuse Patterns Using Capture Groups

Tell us what’s happening:
Describe your issue in detail here.

Your code so far
hello, this is my regex but does not work…
let reRegex = /(\d)(\s)\1\2\1/g; // Change this line
**************************** Here’s a breakdown of what each part of the regular expression means:

(\d) - Matches and captures a single digit. The parentheses indicate a capturing group.
(\s) - Matches and captures a single whitespace character.
\1 - Matches the same digit as the one captured in the first capturing group.
\2 - Matches the same whitespace character as the one captured in the second capturing group.
\1 - Matches the same digit as the one captured in the first capturing group.
/g - This flag specifies a global search, so the regular expression will match all occurrences in the input string, not just the first one.

******** please help



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


/*
/(test)(\s)\1\2\1/


let repeatStr = "row row row your boat"
let repeatRegex = /(\w+) \1 \1/;
let result = repeatRegex.test(repeatStr); // Returns true
let result_b = repeatStr.match(repeatRegex); // Returns ["row row row", "row"]
console.log(result);
console.log(result_b );


*/

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0

Challenge: Regular Expressions - Reuse Patterns Using Capture Groups

Link to the challenge:

Regexes can be a bit of a headache!
Here are issues which need to be addressed to solve this challenge:

  1. Your regex should match a repeated number with an unspecified number of digits. Your capture group (\d) will only match single digit numbers.
  2. Using the global flag will allow the entire pattern to be matched multiple times, so even with the correct pattern, you would match ‘42 42 42’ and also ‘42 42 42 42 42 42’ or multiples thereof, for instance.
  3. You need to find a way of limiting the string, so that it can’t anything additional (e.g. ‘42 42 42 abc’). I’d use string anchors.
  4. There is an issue with using (\s) as a capture group as this matches both single whitespaces and tabs. So you would match ‘42 42 42’ but also ‘42\t42\t42’.

The useful thing about repeating capture groups using the \1 syntax is that you can incorporate whitespaces simply by explicitly putting the spaces into the regex pattern.

/(abc)\1\1/ will match 'abcabcabc'
/(abc) \1 \1/ will match 'abc abc abc'

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