Reuse Patterns Using Capture Groups - Give me more examples please

It is confusing. It took me quite a while to wrap my head around the concept of capture groups, but if you have patience, it does make sense.

In your regex:
let reRegex = /(\d+)\s(\d+)\s\3/;

…you start out right: the first parenthesis indicates a capture group. Later on IN THAT SAME REGEX, you can refer to that first capture group by \1. The second set of parenthesis, however, are creating a second capture group, which you could refer to as \2.

Instead, where you want to have three instances of the same thing, try something like:

let reRegex = /(\d+)\s\1\s\1/;

This indicates a capture group, whitespace, another instance of the same capture group, whitespace, and a third instance of that same capture group.

It actually took a LONG stretch on a regex tester for me to grok this concept. it’s not easy.

Of course, I haven’t GIVEN you the answer. It will still fail, there are a couple more things you want to be watching for in that regex string, but that will take care of your capture group question…

6 Likes