How to use regex to match all sentences that may have a list of stopwords inside them?

Viewed 494

The goal is to find all sentences that may contain a list of stopwords in between the phrase to_match like these:

  • make wish
  • make a wish
  • make the a wish
let stopword: string[]= ["of", "the", "a"];
let to_match : string = "make wish";
let text: string = "make wish wish make a wish wish wish make the a wish make";

I can only match make wish using this regex:

const regex = new RegExp(`(?:\\b)$to_match(?:\\b)`, "gi"); 

I'm wondering if it's possible to do something like

let to_match_splitted: string[] = to_match.split(" ");
const regex = `(?:\\b)${to_match_splitted[0]}\s(${any(stopword)}?)+\s${to_match_splited[1]}(?:\\b)`;

With any(stopword) being something that match any stopword in stopword list.

And having a regex that works whatever is the length of the to_match_splitted with one or many stopwords between each string in the list.

1 Answers

You may create a regex like

/\bmake(?:\s+(?:of|the|a))*\s+wish\b/gi

See the regex demo. Details

  • \b - a word boundary
  • make - a word
  • (?:\s+(?:of|the|a))* - 0 or more occurrences of
    • \s+ - 1+ whitespaces
    • (?:of|the|a) - either of, the or a (you might want to use an? to also match an)
  • \s+ - 1+ whitespaces
  • wish - a word wish
  • \b - a word boundary

In your code, you may use

let stopword: string[]= ["of", "the", "a"];
let to_match : string = "make wish";
let text: string = "make wish wish make a wish wish wish make the a wish make";
const regex = new RegExp(`\\b${to_match.split(/\s+/).join("(?:\\s+(?:" + stopword.join("|") + "))*\\s+")}\\b`, "gi"); 
console.log(text.match(regex));

See the online demo

Related