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

标签 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";

我只能使用此正则表达式匹配许愿:

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

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

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

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

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

最佳答案

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

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

请参阅regex demo详细信息

  • \b - 单词边界
  • make - 一个词
  • (?:\s+(?:of|the|a))* - 0 次或多次出现
    • \s+ - 1 个以上空格
    • (?:of|the|a) - ofthea(您可能会想要使用 an? 来匹配 an)
  • \s+ - 1 个以上空格
  • wish - 一个词wish
  • \b - 单词边界

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

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));

请参阅online demo

关于javascript - 如何使用正则表达式来匹配所有可能包含停用词列表的句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61749427/

相关文章:

javascript - 数据来自API,但不显示。 Angular 9 ABP 框架

javascript - 如何仅从 moment 对象中提取日期

javascript - 我的 jquery 脚本从不执行,我认为这是类选择器的问题

javascript - 用于本地 NodeJS 开发的 Docker

javascript - Typescript - 不同文件中的模块函数引用 - "could not find symbol"

TypeScript:如何处理泛型类型和 keyof 运算符

java - 将 javascript 标签添加到 vaadin UI head

java.util.regex

regex - 正则表达式匹配后删除文本的有效方法

javascript - 需要 Javascript 正则表达式来匹配 URL 中的语言参数