javascript - 正则表达式匹配可能被另一个单词分隔的多个单词,给出可能的中间单词列表
问题描述
我想马赫make wish
,make a wish
并make a the wish
给出to_match
,stopword
列表和text
使用正则表达式:
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";
我只能make wish
使用这个正则表达式进行匹配:
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
请参阅正则表达式演示。细节
\b
- 单词边界make
- 一个字(?:\s+(?:of|the|a))*
- 0 次或多次出现\s+
- 1+ 空格(?:of|the|a)
- 要么of
,the
要么a
(您可能还想使用an?
to 匹配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));
查看在线演示