【问题标题】:JavaScript match against arrayJavaScript 匹配数组
【发布时间】:2011-06-02 20:25:19
【问题描述】:

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

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。

【问题讨论】:

  • 我想使用数组而不是 | 的原因数组可能会变大,有数百个条目
  • 句子“The Caterpillar ...”中包含“cat”作为另一个词的一部分呢?
  • 没关系...如果需要,我可以调整正则表达式的单词边界
  • @xivix:所以你在寻找严格匹配,对吧?因为在这种情况下,有一种更有效的方法。
  • 不确定您所说的严格匹配是什么意思。该示例已简化,但我将使用各种正则表达式功能将各种比较字符串与输入字符串匹配。例如,如果我想隔离 cat 我会使用 \bcat\b

标签: javascript arrays match


【解决方案1】:

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

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

演示:

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

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

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

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

演示:

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

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

【讨论】:

  • 嗯,这就是我上面提到的 bar 方法。我知道如何用条形设置一个长的正则表达式......但它最终会成为一个非常长的正则表达式,我希望有一个更优雅/有效的解决方案。只是想知道 Javascript 是否有任何内置功能可以解决这个问题。
  • 如果没有优雅的方法来做到这一点,那么循环遍历数组并运行简单的正则表达式 x 次会更好吗?还是将所有正则表达式放在一个长而复杂的正则表达式中?
  • 这行得通。谢谢 :) 它似乎比我使用的方法更有效。
  • 只是想补充一点,我的包npm.im/regexr 可能有助于简化正则表达式操作(不需要转义)。
【解决方案2】:

(多年后)

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

var corsWhitelist = [/^(?:.+\.)?domain\.com/, /^(?:.+\.)?otherdomain\.com/];

var corsCheck = function(origin, callback) {
  if (corsWhitelist.some(function(item) {
    return (new RegExp(item).test(origin));
  })) {
    callback(null, true);
  } 
  else {
    callback(null, false);
  }
}

corsCheck('otherdomain.com', function(err, result) {
  console.log('CORS match for otherdomain.com: ' + result);  
});

corsCheck('forbiddendomain.com', function(err, result) {
  console.log('CORS match for forbiddendomain.com: ' + result);  
});

【讨论】:

    【解决方案3】:

    如果您想匹配一个名为 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.
     */
    

    【讨论】:

      【解决方案4】:

      这样好吗?

      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));
      

      【讨论】:

      • 嗯,谢谢,但我已经知道如何循环遍历数组,这就是我现在正在做的事情。我想上面 Gaby 提到的 SOME 函数是我要找到的最接近的函数。
      猜你喜欢
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 2023-03-08
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      相关资源
      最近更新 更多