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 are going to delve deep into the 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 thing we matched, \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:

const pattern = /(\w+)\s\1/; const str = 'hello hello'; console.log(pattern.test(str)); // Output: true

In this example, \1 refers to the first word we matched. The whole expression therefore, matches if there is a word that is repeated again, and that is the reason 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 discussed also the named groups. Here's a simple example:

const pattern = /(?<word>\w+)\s\k<word>/; const str = 'world world'; const match = pattern.exec(str); console.log(match.groups.word); // Output: world

In this example, \<word> is a named group. We use \k<word> to refer to this named group later.

Advanced Uses

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

Conditional Matching

We can use backreferences to match something only if something else is true. For example:

const pattern = /(\d+)(?=\d)(?!\1)/; const str = '12'; console.log(pattern.test(str)); // Output: true const secondStr = '11' console.log(pattern.test(secondStr)); // Output: false

Here, \1 is the number we matched before. The pattern matches a number only if it's not the same as the one before it.

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 Your Knowledge

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

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?