gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:31:18 28 4
gpt4 key购买 nike

目标是找到在短语 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com