0

在这个正则表达式多次捕获中,我必须添加“g”标志来获取所有项目......

"aaa bbb ccc \n.000.\n \n.111.\n sd555 dsf \n.222.\n ddd ".match( /^.(.*).$/gm )

当我添加“g”(全局)标志时?如何访问捕获的组......应该有 3 个像 [“000”,“111”,“222”] 但我不知道如何访问它们。 .. 我不断得到 [".000.", ".111.", ".222."] << 注意单词前后的点

4

3 回答 3

5

如果你想在全局正则表达式中获取捕获组,你不能使用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之前的正则表达式。)

于 2012-06-07T21:14:06.533 回答
0

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

演示在这里。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/>' );
于 2012-06-07T21:14:22.280 回答
0

在 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]where n 是你想要的匹配,比如 `hello[1].

但是,如果您只想匹配某些内容,则需要修改您的正则表达式。

于 2012-06-07T21:15:04.057 回答