Contact Us or call 1-877-932-8228


Backreferences are special wildcards that refer back to a subpattern within a pattern. They can be used to make sure that two subpatterns match. The first subpattern in a pattern is referenced as \1, the second is referenced as \2, and so on.

For example, the pattern ([bmpw])o\1 matches "bob", "mom", "pop", and "wow", but not "bop" or "pow".

A more practical example has to do matching the delimiter in social security numbers. Examine the following regular expression:

^\d{3}([\- ]?)\d{2}([\- ]?)\d{4}$

Within the caret (^) and dollar sign ($), which are used to specify the beginning and end of the pattern, there are three sequences of digits, optionally separated by a hyphen or a space. This pattern will be matched in all of the following strings (and more):

  • 123-45-6789
  • 123 45 6789
  • 123456789
  • 123-45 6789
  • 123 45-6789
  • 123-456789

The last three strings are not ideal, but they do match the pattern. Backreferences can be used to make sure that the second delimiter matches the first delimiter. The regular expression would look like this.

^\d{3}([\- ]?)\d{2}\1\d{4}$

The \1 refers back to the first subpattern. Only the first three strings listed above match this regular expression.