【问题标题】:Find all matches in string with regex in any order with Javascript使用Javascript以任何顺序使用正则表达式查找字符串中的所有匹配项
【发布时间】:2021-05-09 22:01:43
【问题描述】:

我如何在下面找到所有匹配项?我现在的方法是从关键字数组中找到 any 匹配项,但是,由于存在单词“not”,因此在控制台中匹配项应该为空。

var title = "How to edit an image";
var keywords = ["image","edit","not"];
var matches = [];
if (title.search(new RegExp(keywords.join("|"),"i")) != -1) {
     matches.push(title);
}
console.log(matches);

【问题讨论】:

  • 预期输出是什么?
  • 由于关键字中存在“not”一词,因此控制台的输出应为空白,因为“not”不在标题中。
  • 你可以试试这样的keywords.every(word => title.includes(word))。当您的所有单词不在title 中时,它将返回false
  • 有没有兼容ie11的版本,我得支持那个浏览器
  • 您可以使用indexOf() 获取 IE 支持

标签: javascript


【解决方案1】:

不需要正则表达式,只需使用 every() 遍历单词,然后使用 includes() 检查每个关键字(见下文);

console.log(Check("How to edit an image", ["image","edit","not"])); // false
console.log(Check("How to edit an image", ["image","edit"]));       // true

function Check(title, keywords) {
    return keywords.every(word => title.indexOf(word) > -1);
}

注意:使用title.indexOf(word) > -1 支持 IE 11 作为 OP 请求。


编辑;基于OP的评论;

keywords 数组中删除"not" 以确保逻辑有效

var title = "How to edit an image";
var keywords = ["image","edit","not"];
var matches = [];
if (keywords.every(word => title.indexOf(word) > -1)) {
     matches.push(title);
}
console.log(matches);

【讨论】:

  • 我不知道如何将它纳入我的逻辑,在这里有点挣扎,你能将你的代码结合到我上面的帖子中,没有箭头功能
  • 0stone0,你还在用箭头函数!
  • 我对其进行了一些更改以删除它: function findMatch(title, keywords) { return keywords.every(function(word) { return title.indexOf(word) > -1; }) }
【解决方案2】:

你不需要正则表达式。只需映射关键字

const output= keywords.map(x=>
    title.indexOf(x)!==-1 ? title : ""
);

//output
["How to edit an image", "How to edit an image", ""]

【讨论】:

  • 如何将它添加到我上面的代码中,没有箭头功能?
【解决方案3】:

使用这个answer作为参考,如果你固定使用Regex,你应该使用lookarounds

^(?=.*\bimage\b)(?=.*\bedit\b)(?=.*\bnot\b).*$

应用在您的 Javascript 代码上,它会是这样的:

var title = "How to edit an image";
var title2 = "How to not edit an image";
var keywords = ["image","edit","not"];
var matches = [];

// Using for block because I don't remember if forof, forin or foreach are supported by IE 11
var regex = "^";
for (var i = 0; i < keywords.length; i++) {
    regex += "(?=.*\\b" + keywords[i] + "\\b)"; // Needed beacuse template Strings are not supported by IE 11.
}
regex += ".*$"

if (title.search(new RegExp(regex,"i")) != -1) {
    matches.push(title);
}
console.log(matches);

if (title2.search(new RegExp(regex,"i")) != -1) {
    matches.push(title2);
}
console.log(matches);

【讨论】:

  • 说实话,@0stone0 的答案在使用方面要好得多。仅当您真的想使用正则表达式时,我才发布此解决方案。
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
相关资源
最近更新 更多