我有这个文字
txt = "Local residents o1__have called g__in o22__with reports...";
我需要在每个o
和__
如果我这样做
txt.match(/o([0-9]+)__/g);
我会得到
["o1__", "o22__"]
但我想要
["1", "22"]
我该怎么做?
答案 0 :(得分:18)
请参阅this question:
txt = "Local residents o1__have called g__in o22__with reports...";
var regex = /o([0-9]+)__/g
var matches = [];
var match = regex.exec(txt);
while (match != null) {
matches.push(match[1]);
match = regex.exec(txt);
}
alert(matches);
答案 1 :(得分:13)
你需要在正则表达式对象上使用.exec()
并使用g标志重复调用它以获得如下的连续匹配:
var txt = "Local residents o1__have called g__in o22__with reports...";
var re = /o([0-9]+)__/g;
var matches;
while ((matches = re.exec(txt)) != null) {
alert(matches[1]);
}
上一场比赛的状态作为lastIndex
存储在正则表达式对象中,这就是下一场比赛用作起点的位置。
您可以在此处查看:http://jsfiddle.net/jfriend00/UtF6J/
这里使用正则表达式来描述:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec。
答案 2 :(得分:3)
/o([0-9]+?)__/g
这应该有效。 Click here并搜索“懒星”。
var rx = new RegExp( /o([0-9]+?)__/g );
var txt = "Local residents o1__have called g__in o22__with reports...";
var mtc = [];
while( (match = rx.exec( txt )) != null ) {
alert( match[1] );
mtc.push(match[1]);
}
Jek-fdrv在评论中指出,如果你在while循环之前调用rx.test,则会跳过一些结果。那是因为RegExp对象包含一个lastIndex字段,用于跟踪字符串中最后一个匹配的索引。当lastIndex更改时,RegExp通过从其lastIndex值开始保持匹配,因此跳过字符串的一部分。一个小例子可能会有所帮助:
var rx = new RegExp( /o([0-9]+?)__/g );
var txt = "Local residents o1__have called g__in o22__with reports...";
var mtc = [];
console.log(rx.test(txt), rx.lastIndex); //outputs "true 20"
console.log(rx.test(txt), rx.lastIndex); //outputs "true 43"
console.log(rx.test(txt), rx.lastIndex); //outputs "false 0" !!!
rx.lastIndex = 0; //manually reset lastIndex field works in Chrome
//now everything works fine
while( (match = rx.exec( txt )) != null ) {
console.log( match[1] );
mtc.push(match[1]);
}