如何使用正则表达式来匹配所有可能包含停用词列表的句子?

Vee*_*Vee 2 javascript regex typescript

目标是找到在短语之间可能包含停用词列表的所有句子,to_match如下所示:

  • 许愿
  • 许个愿
  • 许愿
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";
Run Code Online (Sandbox Code Playgroud)

我只能make wish使用这个正则表达式进行匹配:

const regex = new RegExp(`(?:\\b)$to_match(?:\\b)`, "gi"); 
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以做类似的事情

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

any(stopword)停用词列表中的任何停用词相匹配。

to_match_splitted并且有一个正则表达式,无论列表中每个字符串之间有一个或多个停用词的长度如何,都可以工作。

Wik*_*żew 5

您可以创建一个正则表达式,例如

/\bmake(?:\s+(?:of|the|a))*\s+wish\b/gi
Run Code Online (Sandbox Code Playgroud)

请参阅正则表达式演示细节

  • \b- 单词边界
  • make- 一个字
  • (?:\s+(?:of|the|a))*- 0次或多次出现
    • \s+- 1+ 空格
    • (?:of|the|a)- 要么of,the要么a(你可能还想用an?它来匹配an
  • \s+- 1+ 空格
  • wish- 一个字wish
  • \b- 单词边界

在您的代码中,您可以使用

/\bmake(?:\s+(?:of|the|a))*\s+wish\b/gi
Run Code Online (Sandbox Code Playgroud)

查看在线演示