Javascript - 正则表达式访问多次出现

Pie*_*NAY 14 javascript regex

我有这个文字

txt = "Local residents o1__have called g__in o22__with reports...";
Run Code Online (Sandbox Code Playgroud)

我需要在每个o和之间得到数字列表__

如果我做

txt.match(/o([0-9]+)__/g);
Run Code Online (Sandbox Code Playgroud)

我会得到

["o1__", "o22__"]
Run Code Online (Sandbox Code Playgroud)

但我想拥有

["1", "22"]
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点 ?

sol*_*oth 22

看到这个问题:

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);
Run Code Online (Sandbox Code Playgroud)

  • 造成无限循环 (8认同)
  • 好的,让我们验证你的,你需要比@jfriend00 :)更多的声誉 (2认同)

jfr*_*d00 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]);
}
Run Code Online (Sandbox Code Playgroud)

上一个匹配的状态存储在正则表达式对象中lastIndex,这就是下一个匹配用作起点的内容.

你可以在这里看到它的工作:http://jsfiddle.net/jfriend00/UtF6J/

使用regexp这种方式在这里描述:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec.