Regexmatch to find all string cells that match multiple words

Viewed 17419

I'm using ArrayFormula and FILTER combination to list all cells in a column that contain all of the search term words. I'm using REGEXMATCH rather than QUERY/CONTAINS/LIKE because my FILTER has other criteria that return TRUE/FALSE.

My problem seems to be precedence. So the following regex works in a limited way.

=ArrayFormula(filter(A1:A5,regexmatch(A1:A5,"(?i)^"&"(.*?\bbob\b)(.*?\bcat\b)"&".*$")))

It will find Bob and cat but only if Bob precedes cat.

Google sheets fails if I try to use lookahead ?= ie

=ArrayFormula(filter(A1:A5,regexmatch(A1:A5,"(?i)^"&"(?=.*?\bbob\b)(?=.*?\bcat\b)"&".*$")))

I don't want to use the '|' alternation in the string (repeat and reverse) as the input words may be many more than two so alternation becomes exponentially more complex.

Here's the test search array (each row is a single cell containing a string)...

Bob ate the dead cat
The cat ate live bob
No cat ate live dog
Bob is dead
Bob and the cat are alive

... and the desired results I'm after.

Bob ate the dead cat
The cat ate live bob
Bob and the cat are alive

Once I have the regex sorted out, the final solution will be a user input text box where they simply enter the words that must be found in a string ie 'Bob cat'. This input string I think I can unpack into its separate words and concatenate to the above expression, however, if there's a 'best practice' way of doing this I'd like to hear.

3 Answers

Maybe a bit easier to understand (I hate MMULT)

=query({A1:A},"select Col1 where "&join(" and ",arrayformula("Col1 matches '."&filter(B:B,B:B<>"")&".'")))

Where A contains your list of phrases and B contains your criteria words.

This part of the formula, =join(" and ",arrayformula("Col1 matches '."&filter(D3:D,D3:D<>"")&".'")) builds a query string from terms in B. for example:

Col1 matches '.cats.' and Col1 matches '.dogs.'

And then this list gets concatenated into the whole "select" expression:

select Col1 where Col1 matches '.cats.' and Col1 matches '.dogs.'

Related