Skip to content

Regex backreferences in pattern: \n and \k<name>

Backreferences, a key feature of regular expressions, enable developers to reference previously captured groups within the pattern itself. In this guide, we will delve deep into backreferences.

How to Use Backreferences

In JavaScript, we use a backslash followed by a number to refer to a part of the pattern we already matched. For example, \1 refers to the first captured group, \2 refers to the second, and so on. We can also give names to parts of our pattern and use those names later.

Let's see an example:


Output appears here after Run.

In this example, \1 refers to the first captured group. The whole expression, therefore, matches if a word is repeated, which is why the pattern matches "hello hello".

Using Named Groups

Instead of using numbers, we can give names to parts of our pattern. This makes it easier to understand. For more information, check the previous page, Capturing Groups, where we also discussed named groups. Here's a simple example:


Output appears here after Run.

In this example, (?<word>\w+) is a named group. We use \k<word> to refer to this named group later.

Note: Named groups and \k<name> backreferences are supported in all modern browsers and Node.js environments without flags.

Advanced Uses

Backreferences can do more than just repeat things. Let's look at an advanced example:

Matching Consecutive Digits

We can use backreferences to match a digit only if the immediately following digit is different. For example:


Output appears here after Run.

Here, \1 is the digit we matched before. The pattern matches a digit only if the following digit is different from the captured one. This technique is useful for validating sequences where adjacent characters must differ, such as certain password rules or data formats.

Note: While powerful, backreferences can impact performance on large strings. Some regex engines also have limitations when using backreferences inside lookarounds, so test patterns carefully in your target environment.

Conclusion

Understanding backreferences in JavaScript regular expressions helps us do advanced text matching tasks. By knowing how to use them, we can solve complex problems more easily. Try using these techniques in your own JavaScript projects!

Practice

Which of the following statements about backreferences in JavaScript regular expressions is true?

Dual-run preview — compare with live Symfony routes.