JavaScript 与数组匹配

发布于 2024-11-13 20:55:49 字数 430 浏览 3 评论 0原文

我想知道如何将字符串与正则表达式数组进行匹配。
我知道如何循环遍历数组。
我也知道如何通过制作一个由 |
分隔的长正则表达式来做到这一点 我希望有一种更有效的方法

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 =“她告诉我鸟可以飞,我同意” 将返回 true。

I would like to know how to match a string against an array of regular expressions.
I know how to do this looping through the array.
I also know how to do this by making a long regular expression separated by |
I was hoping for a more efficient way like

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

For example:

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

In the above example, the condition would be false.
However, string = "She told me birds can fly and I agreed" would return true.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

阪姬 2024-11-20 20:55:49

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

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

How about creating a regular expression on the fly when you need it (assuming the array changes over time)

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

demo:

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


For browsers that support javascript version 1.6 you can use the some() method

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

demo:

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

2024-11-20 20:55:49

(多年后)

我的@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);  
});

(Many years later)

My version of @Gaby's answer, as I needed a way to check CORS origin against regular expressions in an array:

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);  
});
徒留西风 2024-11-20 20:55:49

可以吗?

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

Is that ok ?

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));
痴情 2024-11-20 20:55:49

如果您想要匹配名为 strings 的数组中的文字字符串,则可以通过执行以下操作将它们组合成一个替换:

new RegExp(strings.map(
    function (x) {  // Escape special characters like '|' and '

如果您不仅仅只有文字字符串,您想要组合正则表达式,那么您使用 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.
 */
. return x.replace(/[^a-zA-Z]/g, "\\
amp;");
    }).join("|"))

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

If you have the literal strings in an array called strings you want to match, you can combine them into an alternation by doing

new RegExp(strings.map(
    function (x) {  // Escape special characters like '|' and '

If you don't have only literal strings, you want to combine regular expressions, then you use 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.
 */
. return x.replace(/[^a-zA-Z]/g, "\\
amp;");
    }).join("|"))

If you don't have only literal strings, you want to combine regular expressions, then you use http://code.google.com/p/google-code-prettify/source/browse/trunk/js-modules/combinePrefixPatterns.js

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文