![](/img/trans.png)
[英]Using a regular expression in JavaScript, how do I group my matches?
[英]How can I call a function from regular expression matches in javascript
我有一个正则表达式,我想知道是否可以将所有匹配项用作函数的参数。 例如,假设我有一个数据集
Hello heelo hhhheEEeloo eelloooo
和一个正则表达式
/[Hh]{1,}[Ee]{1,}[Ll]{1,}[Oo]{1,}/
哪个会匹配
Hello heelo hhhheEEeloo
我如何获得一个javascript函数以将每个匹配项作为参数,例如
function isHello(arg) {
if (arg == 'Hello') { return 1 }
else { return 0}
}
将.replace
与回调一起使用
"Hello heelo hhhheEEeloo eelloooo".replace(/[Hh]{1,}[Ee]{1,}[Ll]{1,}[Oo]{1,}/g,function(match){
//Your function code here
return match;
})
或更简单的例子:
var count=0;
"aaaaaaa".replace(/a/g,function(match){
console.log("I matched another 'a'",count++);
// just to not replace anything, technically this doesn't matter
//since it doesn't operate on the actual string
return match;
});
var string = "Hello heelo hhhheEEeloo eelloooo",
regex = /[Hh]{1,}[Ee]{1,}[Ll]{1,}[Oo]{1,}/g,
fn = function(arg){
if (arg == 'Hello')
return 1;
return 0
};
string.match(regex).forEach(fn);
注意添加到正则表达式中的g
标志进行匹配,以提供所需的匹配。
这是使用match()
的示例:
var s = "Hello heelo hhhheEEeloo eelloooo";
s.match(/[Hh]{1,}[Ee]{1,}[Ll]{1,}[Oo]{1,}/g).forEach(function(entry) {
// your function code here, the following is just an example
if (entry === "Hello")
console.log("Found Hello!");
else
console.log(entry + " is not Hello");
return;
});
示例: http : //jsfiddle.net/wTMuF/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.