访问多个捕获的正则表达式(新手的事情...)(Accessing multiple captures

2019-09-17 21:19发布

在此正则表达式多个捕获我要加“G”标志,以获得所有项目...

“AAA BBB CCC \ n.000。\ n \ n.111。\ n sd555 DSF \ n.222。\ n DDD” .match(/^.(.*).$/gm)

当我添加了“G”(global)标志?如何访问捕获组...应该有3如[“000”,“111”,“222”],但我不知道如何访问它们。 ..我不断收到[“.000‘’0.111‘’0.222”。] <<前注意点和后话

Answer 1:

如果你想捕捉组在全球正则表达式,则不能使用match ,很遗憾。 相反,你需要使用exec的正则表达式:

var myregex = /^.(.*).$/gm;
var result, allMatches = [];
while((result = myregex.exec(mystring)) != null) {
    var match = result[1]; // get the first match pattern of this match
    allMatches.push(match);
}

随着全球性的正则表达式, match返回所有整个比赛的阵列和永远不会返回捕捉组。 exec返回单个匹配及其所有捕获组。 为了让所有的比赛,你必须调用exec多次,直到它最后返回null

需要注意的是exec依赖于正则表达式保持状态,所以必须保存在正则表达式的变量:

while((result = /^.(.*).$/gm.exec(mystring)) != null) // BAD and WRONG!

这是错误的,因为每个循环中,有一个新的正则表达式不知道它是应该回到这个循环什么比赛。 (或者,更准确地说,它不知道lastIndex以前的正则表达式。)



Answer 2:

在Firebug:

var hello = "aaa bbb ccc \n.000.\n \n.111.\n sd555 dsf \n.222.\n ddd ".match( /^.(.*).$/gm );
console.dir(hello);

然后你可以使用hello[n]其中n是你想要的比赛,比如'你好[1]。

然而,你需要修改你的正则表达式,如果你只想匹配某些事情。



Answer 3:

从str.match(重新)返回的结果是一个数组。

演示在这里。 http://jsfiddle.net/rXgQa/

var re = /^.(.*).$/gm;
var str = "aaa bbb ccc \n.000.\n \n.111.\n sd555 dsf \n.222.\n ddd ";
var matches = str.match( re );
if( matches ){
    document.body.innerHTML += matches.join( '<br/> ' );
}​

输出:

aaa bbb ccc // matches[0]
.000.     // matches[1]
.111.     // matches[2]
sd555 dsf // matches[3]
.222.     // matches[4]
ddd       // matches[5]

更新

这里是我的问题的答案的第二部分。 问:如何前和后的数字摆脱了点?

我的回答:我会通过比赛,只是循环使用空字符串替换点。 此外,因为你需要躲避点正则表达式是错误的。

更新的jsfiddle演示: http://jsfiddle.net/rXgQa/1/

var re = /^\.([^\.]+)\.$/gm;
var lines = "aaa bbb ccc \n.000.\n \n.111.\n sd555 dsf \n.222.\n ddd ";
var matches = lines.match( re );
var i = (matches||[]).length;
while( i-- ){
    matches[i] = matches[i].replace( /\./g, '' );
}

document.body.innerHTML += matches.join( '<br/>' );


文章来源: Accessing multiple captures in a RegEx (Newbie thing…)