Reuse Patterns Using Capture Groups

Can someone please explain me this part from this class:

The substring matched by the group is saved to a temporary "variable", which can be accessed within the same regex using a backslash and the number of the capture group (e.g. \1 ). Capture groups are automatically numbered by the position of their opening parentheses (left to right), starting at 1.

Specifically the use of \1. How does it work?


It might be better if you explain what you are having trouble with.

The use of \1. How does it work ?

The parentheses create a capture group, and whatever is in the parentheses gets saved to a temporary variable. The first set of parentheses saves the content to the temporary variable \1. The second set of parentheses saves to the temporary variable \2. And so on. You can use these temporary variables elsewhere in the same regular expression.

/(\w+) \1/

This says to find an alphanumeric string ((\w+)) that is then repeated immediately after a space. The string inside the parentheses is saved to the temporary variable \1 and then \1 is used in the regular expression to say “match the same string that was found in the first capture group”.

So this pattern would match

row row

Because the first row is captured in the parentheses and so \1 also has the value row. But it wouldn’t match

row boat

Because boat is not the value of \1.

1 Like

Thank you very much for your kind reply!! Now I understand the \1 :star_struck: :star_struck: