Eradicator_1729
Eradicator_1729

Reputation: 180

Regular Expression to match two words in either order with a specific third word between them

I looked through a lot of other questions and just didn't quite see what I think would work for me. Basically I want to match three words exactly: "cat", "and", "dog" where "and" is always in the middle but "cat" and "dog" can be on either side. I have used lookarounds to match "cat" and "dog" in either order, but I can't figure out how to integrate a test for the "and" in the middle. What I currently have is this:

^(?=.*\bcat\b)(?=.*\bdog\b).*$

but this accepts any word between the two.

Upvotes: 0

Views: 769

Answers (1)

TonyR
TonyR

Reputation: 126

If duplicates are not a problem, \b((cat\sand\sdog)|(dog\sand\scat))\b is the simplest solution, otherwise \b((cat\sand\sdog)|(dog\sand\scat))\b

Upvotes: 1

Related Questions