首页 > 解决方案 > 正则表达式匹配可能被另一个单词分隔的多个单词,给出可能的中间单词列表

问题描述

我想马赫make wishmake a wishmake a the wish给出to_matchstopword列表和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并且有一个正则表达式,无论列表中每个字符串之间的一个或多个停用词的长度如何。

标签: javascriptregextypescript

解决方案


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

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

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

  • \b- 单词边界
  • make- 一个字
  • (?:\s+(?:of|the|a))*- 0 次或多次出现
    • \s+- 1+ 空格
    • (?:of|the|a)- 要么ofthe要么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));

查看在线演示


推荐阅读