A capturing group (...)
groups a subpattern. For example, ([A-Z]\d)
matches a letter followed by a digit, like "A1". A backreference, denoted by \1
, \2
, etc., refers to a previous capturing group and matches the same text as that group.
For instance, in the pattern ([A-Z]\d)\1
, \1
refers to the first capturing group ([A-Z]\d)
, ensuring that the same letter-digit combination is repeated.
const pattern = /([A-Z]\d)\1/;
pattern.test("A1A1"); // true
pattern.test("A1B1"); // false
You can also use a backreference with quantifiers:
const pattern = /(\d)\1{2}/;
pattern.test("111"); // true
pattern.test("122"); // false