Javascript - Regex access multiple occurrences
本问题已经有最佳答案,请猛点这里访问。
我有这个短信
1 | txt ="Local residents o1__have called g__in o22__with reports..."; |
其中我需要得到每个
如果我这样做
1 | txt.match(/o([0-9]+)__/g); |
我会得到
1 | ["o1__","o22__"] |
但是我想要
1 | ["1","22"] |
我该怎么做?
请参阅此问题:
1 2 3 4 5 6 7 8 9 | 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 2 3 4 5 6 | 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]); } |
上一个匹配的状态存储在正则表达式对象中,作为
你可以在这里看到它的工作:http://jsfiddle.net/jfriend00/utf6j/
使用regexp的方法如下:https://developer.mozilla.org/en/javascript/reference/global_objects/regexp/exec。
1 | /o([0-9]+?)__/g |
这应该有效。点击这里搜索"懒星"。
1 2 3 4 5 6 7 | 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对象包含一个last index字段,用于跟踪字符串中最后一个匹配的索引。当lastindex更改时,regexp通过从其lastindex值开始保持匹配,因此跳过字符串的一部分。举个小例子可能会有所帮助:
1 2 3 4 5 6 7 8 9 10 11 12 | 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]); } |