How to extract phrases that are part of a list in a string using REGEX (Preferably Google Sheets, but any program can be translated)

Viewed 37

For example, I have a list of phrases/words ("boy, a guy, tree") and I want them to be the result if written in a string and remove duplicate

Desired Outcome:
Input: boy girl a tree a guy and a boy
Output: boy tree a guy (in any particular order, I don't mind)

Input: boy boy boy boy boy
Output: boy

Input: girl boy girl boy a guy
Output: girl boy a guy (in any particular order, I don't mind)

Input: a guy girl very handsome girl tricky question
Output: a guy girl

2 Answers

This work for me:

=TRIM(JOIN(" ",BYROW({"boy","girl","a guy","tree"};LAMBDA(R,IFERROR(REGEXEXTRACT(A1,R))))))

here the test sheet, you can choose words in a first range.

In your examples girl is not declared and not even extracted .

You can filter the target words and on the filter callback, you check if the str includes each word of these, and after filteration then join with a white space.

const words = ['boy', 'girl', 'a guy'];

function getWords(str) {
  return words.filter(w => str.includes(w)).join(' ');
}

console.log(getWords("boy boy boy boy boy")) // boy

console.log(getWords("girl boy girl boy a guy Output: girl boy a guy")) // girl boy a guy

console.log(getWords("a guy girl very handsome girl tricky question")) // a guy girl

Related