dakab
dakab

Reputation: 5875

How to re-use a capturing group to match a different alternation choice?

I have a group of words and another group with a conjunction. I’m looking for a regular expression that matches any single one of those words, demanding the conjunction in between:


Practical example: Consider this platform-agnostic regex: /(Huey|Dewey|Louie) and \1/.

I want it to match “Huey and Louie” or “Dewey and Huey”, but it only matches “Huey and Huey”, because backreferences merely match previously matched texts.

I could repeat myself by using /(Huey|Dewey|Louie) and (Huey|Dewey|Louie)/ but I think there’s a smarter way of re-using capturing groups at a later time. Is that feasible somehow?

Upvotes: 3

Views: 510

Answers (1)

melpomene
melpomene

Reputation: 85767

You can do this if you're using Perl (or a language with sufficiently compatible regexes):

/(Huey|Dewey|Louie) and (?1)/

The (?N) part is a "recursive subpattern", matching the same thing as the subregex in capturing group N. (The difference between this and backreferences like \N is that \N matches the same string that was matched by the capturing group. (?N) reuses the regex itself.)

Upvotes: 4

Related Questions