javascript 将单词(字符串)数组转换为正则表达式并使用它来获取字符串的匹配项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28280920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:43:15  来源:igfitidea点击:

convert array of words (strings) to regex and use it to get matches on a string

javascriptarraysregexstring

提问by kuus

What is the most concise and efficient way to translate an array of strings in a regex and then use the regex multiple times on different strings to get the result matches and then iterate over them? Now I'm using the following:

翻译正则表达式中的字符串数组,然后在不同的字符串上多次使用正则表达式以获得结果匹配,然后迭代它们的最简洁和有效的方法是什么?现在我正在使用以下内容:

var myArray = ['peaches', 'bananas', 'papaya', 'supercity'];
var myString = 'I want some papaya and some peaches';

var regexFromMyArray = new RegExp(myArray.toString().replace(/,/g, '|'), 'gi');

var matches = myString.match(regexFromMyArray) || [];

if (matches.length) {
  for (var i = 0, l = matches.length; i < l; i++) {
    console.log('Found: ' + matches[i]);
  }
}

performance is important here, so plain javascript please.

性能在这里很重要,所以请使用简单的 javascript。

回答by Amit Joki

Just join with pipeline, using Array.join

只需加入管道,使用 Array.join

var regexFromMyArray = new RegExp(myArray.join("|"), 'gi');

and just do this as ifcondition is just redundant.

并且只是这样做,因为if条件只是多余的。

for(var i = 0; i < matches.length; i++)
   console.log("Found:", matches[i]);
  1. A single method is being used instead of initial 3. (toStringinternally calls join(",")) and replacefunction is also not used.
  2. We have removed an unnecessary if-condition. So that's pretty quick.
  1. 正在使用单个方法而不是初始 3。(toString内部调用join(","))和replace函数也未使用。
  2. 我们删除了一个不必要的 if 条件。所以这很快。

And since you talk about regexes, I'd like to say that

既然你谈论正则表达式,我想说

  1. A single regex initialization isn't going to cost you much.
  2. If your objective is really to match the words in the array, then just go with String.indexOf, which is a non-regex form of solving the same.
  1. 单个正则表达式初始化不会花费太多。
  2. 如果您的目标真的是匹配数组中的单词,那么只需使用String.indexOf,这是解决相同问题的非正则表达式形式。