Skip Navigation LinksHome > Blog > 2008 > January > 01 > How To: match using backreferences

How To: match using backreferences

Backreferencing uses named groups to allow you to search for other instances of characters that match a wildcard. Backreferences provide a convenient way to find repeating groups of characters. They can be thought of as a shorthand instruction to match the same string again.

As the name implies, a regex backreference refers to a substring previously encountered in the target text. Backreferences are denoted by the code \n where n takes values in the range 1..9. Needless to say, one has to instruct the regex engine to keep track of substrings that are to be backreferenced. This is done by placing the substring in parentheses. For instance the pattern Java(script) is a \1ing language. uses the backreference \1 to refer to the substring script. This pattern would validate the phrase "Javascript is a

scripting language but not the phrase "Javascript is a programming language".