Reuse Patterns Using Capture Groups struggle

You can transform /^(\d+)\s\1\s\1$/ to:

  1. ^(\d+) that matches a certain group (in this case any number) and anchor ^ says it must be beginning of the string, and brackets ( ) captures it for later use.
  2. \s that matches one space.
  3. \1 matches group captured in point one.
  4. \s that matches one space.
  5. \1$ matches group captured in point one and anchor $ says it must be the end of the string.

Therefore we have three identical groups separated by space and two conditions: group 1 must be at the beggining of the string and group 3 must be at the end of the string, hence string 42 42 42 will match it, becase first 42 is at the beginning of the string and third 42 is at the end of the string.

But string 42 42 42 42 will not match, because first 42 is at the beginning and third 42 is not at the end (there is also 4th group) - second condition is not fulfilled.
On the other hand if third group would match last 42 (4th) in this string we meet second condition, but first 42 will not be at the beginning (will be 2nd) and in this case first condition is not fullfilled.
So in string:

'42 42 42 42'
 #1 #2 #3 #4

You can’t match #1#2#3, because #3 is not at the end, or #2#3#4, because #2 is not at the beginning.

I hope I explained it simply enough.

7 Likes