3

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:

  • If the words are (A|B|C)
  • and the conjunction is (&)
  • then do match A & C, C & B and even A & A
  • but don’t match A + C, A C or A & D

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?

dakab
  • 5,379
  • 9
  • 43
  • 67

1 Answers1

4

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.)

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • Uhh, recursive subpattern, me likey! This was obviously conceived for this purpose, and it’s clean and short. Even though it might be considered exotic, it seems to be supported by a decent [number of regex engines](http://www.rexegg.com/regex-recursion.html#engines). – dakab Jul 01 '16 at 10:09
  • @SWLim: I know [what to do](http://stackoverflow.com/help/someone-answers) when someone answers. Do you? Because this *isn’t* the right solution for *me*, but it’s a good and correct answer. Still, it’s only fair to wait at least half a day for some more attention. – dakab Jul 01 '16 at 14:19
  • @dakab You have a good point, thank you for pointing that out. Sorry I have assumed from your comment that this answer is the right solution and that you might have forgotten to accept the answer. – swlim Jul 01 '16 at 15:03