目标是找到在短语 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)
-of
、the
或a
(您可能会想要使用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/