I have a variant of exact match that I'm struggling to execute using regex. I would like to match several words (e.g. Apple, Bat, Car) to a string while ignoring order and also being exclusive (i.e. ignoring cases with extra words, or too few words). For example (using the list above), I'd like the following outcomes (true/false):
- Bat, Car, Apple (True)
- Car, Bat, Apple (True)
- Apple, Car, Bat (True)
- Apple, Car, Bat, Stick (False)
- Bat, Car (False)
- Apple (False)
I have tried two things;
(1) lookahead assertions
^(?=.*Apple)(?=.*Bat)(?=.*Car).*
- Bat, Car, Apple (True)
- Car, Bat, Apple (True)
- Apple, Car, Bat (True)
- Apple, Car, Bat, Stick (True)
- Bat, Car (False)
- Apple (False)
This almost works, but allows strings with additional words (e.g. the case with "Stick"). What can I add to exclude these cases, assuming "Stick" can be any other word, and there could be multiple additional words.
(2) Following related Q/A examples on stack overflow
^(Apple|Bat|Car|[,\s])+$
- Bat, Car, Apple (True)
- Car, Bat, Apple (True)
- Apple, Car, Bat (True)
- Apple, Car, Bat, Stick (False)
- Bat, Car (True)
- Apple (True)
Which again almost works, but it incorrectly includes the smaller subsets.
Edit: Note, my list of words to match is just an example, it will be variable and can be any number of words.