Sign in Start free

11Named groups and back references

(?<name>…) gives a group a name; \1 or \k<name> matches the same text again.

Numbers are easy to mix up, so groups can have names: (?<year>\d{4})-(?<month>\d{2}). Named groups are still numbered too.

A back reference matches the very same text a group matched before: (\w+) \1 finds a repeated word like the the. With names, write \k<word>.

A classic use is matching pairs: <(\w+)>.*</\1> matches <b>bold</b> but not <b>bold</i>.

Exercises