转换字(字符串)数组正则表达式,并用它来获得一个字符串匹配 [英] convert array of words (strings) to regex and use it to get matches on a string

查看:292
本文介绍了转换字(字符串)数组正则表达式,并用它来获得一个字符串匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是翻译成一个正则表达式字符串数组,然后用不同的字符串正则表达式多次得到结果的比赛,然后遍历它们最简洁有效的方式?现在,我使用以下内容:

  myarray的无功= ['桃子','香蕉','木瓜,万象'];
VAR的myString ='我想要一些木瓜,桃子一些';VAR regexFromMyArray =新的RegExp(myArray.toString()取代(/,/克,'|'),GI);VAR匹配= myString.match(regexFromMyArray)|| [];如果(matches.length){
  对于(VAR I = 0,1 = matches.length; I<升;我++){
    的console.log('发现:'+匹配[I]);
  }
}

性能是很重要的位置,所以普通的JavaScript,请。


解决方案

刚刚与管道联接,使用 Array.join

  VAR regexFromMyArray =新的RegExp(myArray.join(|),GI);

和刚做这为如果的条件仅仅是多余的。

 为(VAR I = 0; I< matches.length;我++)
   的console.log(发现,匹配[I]);


  1. 正在使用,而不是一个单一的方法最初3(的toString 内部调用加入() )和替换功能也不能使用。

  2. 我们已经删除了不必要的,如果条件。所以这是pretty快。

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


  1. 一个单一的正则表达式的初始化是不会多花费你。

  2. 如果你的目标是真正到阵列中匹配的话,那么就用 String.indexOf 去,这是解决相同的非正则表达式的形式。

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.

解决方案

Just join with pipeline, using Array.join

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

and just do this as if condition is just redundant.

for(var i = 0; i < matches.length; i++)
   console.log("Found:", matches[i]);

  1. A single method is being used instead of initial 3. (toString internally calls join(",")) and replace function is also not used.
  2. We have removed an unnecessary if-condition. So that's pretty quick.

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.

这篇关于转换字(字符串)数组正则表达式,并用它来获得一个字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆