Get startedGet started for free

Backreferences

1. Backreferences

Now you know how to capture parts of a regular expression you are ready to learn how to refer to the captured pieces. Referring to a captured part of a pattern is known as a backreference.

2. Backreferences

Since there may be multiple captures, regular expressions use a simple count from left to right to refer to the different captures. The first capture can be referred to using the REF1 constant in rebus: You can see it translates to a backslash 1 in the regular expression language. The second capture can be referred to using REF2 and so on, up to possible the ninth capture with REF9.

3. In a pattern

Backreferences can be used directly in a pattern, to allow for repeated patterns. This pattern looks for a word by looking for a space then one or more word characters followed by another space.

4. In a pattern

If we capture the word part we can refer to it later and the pattern now picks up repeated words. Backreferences can also be used

5. In a replacement

in the replacement argument to str_replace. The replacement should be a string, so if you want to combine the back reference with some fixed characters, you'll need to combine them with str_c. You could use this to replace the repeated word with a single one. You simply need to replace our match with "a space, then the captured part of the expression"

6. Let's practice!

OK, your turn to practice backreferences.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.