JavaScript与数组匹配

时间:2011-06-02 20:25:19

标签: javascript arrays match

我想知道如何将字符串与正则表达式数组进行匹配 我知道如何在数组中循环。
我也知道如何通过将长的正则表达式分隔为|
来实现 我希望有一种更有效的方式,比如

if (string contains one of the values in array) {

例如:

string = "the word tree is in this sentence";  
array[0] = "dog";  
array[1] = "cat";  
array[2] = "bird";  
array[3] = "birds can fly";  

在上面的例子中,条件是假的 但是,string = "She told me birds can fly and I agreed"将返回true。

4 个答案:

答案 0 :(得分:20)

如何在需要时动态创建正则表达式(假设数组随时间变化

if( (new RegExp( '\\b' + array.join('\\b|\\b') + '\\b') ).test(string) ) {
  alert('match');
}

演示 http://jsfiddle.net/gaby/eM6jU/


对于支持javascript 1.6版的浏览器,您可以使用some()方法

if ( array.some(function(item){return (new RegExp('\\b'+item+'\\b')).test(string);}) ) {
 alert('match');
}

http://jsfiddle.net/gaby/eM6jU/1/

答案 1 :(得分:5)

(许多年后)

我的@Gaby回答的版本,因为我需要一种方法来检查数组中正则表达式的CORS原点:

              Date     Time User% Sys% Wait% Idle% Busy PhysicalCPUs 
1: 01-APR-2015 00:15:28   0.7  0.9   0.1  98.4   NA            64
2: 01-APR-2015 00:30:32   0.7  0.9   0.3  98.1   NA            64
3: 01-APR-2015 00:45:39   0.5  0.7   0.3  98.4   NA            64
4: 01-APR-2015 01:00:46   0.6  0.8   0.3  98.3   NA            64
5: 01-APR-2015 01:15:51   0.5  0.7   0.1  98.6   NA            64

答案 2 :(得分:0)

可以吗?

function checkForMatch(string,array){
    var arrKeys = array.length;
    var match = false;
    var patt;
    for(i=0; i < arrKeys; i++ ){
        patt=new RegExp(" "+array[i]+" ");
        if(patt.test(string))
           match = true;
    }
    return match;
}

string = "She told me birds can fly and I agreed"; 

var array = new Array();
array[0] = "dog";  
array[1] = "cat";  
array[2] = "bird";  
array[3] = "birds can fly";


alert(checkForMatch(string, array));

答案 3 :(得分:0)

如果你想要匹配一个名为strings的数组中的文字字符串,你可以通过

将它们组合成一个交替。
new RegExp(strings.map(
    function (x) {  // Escape special characters like '|' and '$'.
      return x.replace(/[^a-zA-Z]/g, "\\$&");
    }).join("|"))

如果你没有文字字符串,你想组合正则表达式,那么你使用http://code.google.com/p/google-code-prettify/source/browse/trunk/js-modules/combinePrefixPatterns.js

/**
 * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
 * matches the union of the sets of strings matched by the input RegExp.
 * Since it matches globally, if the input strings have a start-of-input
 * anchor (/^.../), it is ignored for the purposes of unioning.
 * @param {Array.<RegExp>} regexs non multiline, non-global regexs.
 * @return {RegExp} a global regex.
 */
相关问题