Reputation: 16085
Regex to match string containing two names in any order has a good explanation of how to match strings in any order. So using
(?=.*\bjack\b)(?=.*\bjames\b)
Will match
jack,james
and
james,jack
However, it will also match
jack,james,jill
How can I construct a regex to match string in any order, but only match those string (i.e. a regex that will match jack and james in any order, but not match a string that contains anything other than jack and james)
Upvotes: 0
Views: 170
Reputation: 5746
It depends on what exactly you mean by "anything other than jack and james", but the general idea would be to match some number of \b(jack|james)\b
, surrounded by other characters:
^\W*(\b(jack|james)\b\W*)*$
You can specify the exact number, or range, of matches instead of using *
. For example, to match exactly 2 or 3 such words:
^\W*(\b(jack|james)\b\W*){2,3}$
Upvotes: 2