regex.match返回正则表达式以及结果?

| 我正在编写一些可捕获用户ID的JavaScript。它可以工作,但是问题是结果中包含了实际的正则表达式。 我的代码:
var regex = /profile\\.php\\?id=(\\d*)/g;
var matches = source.match(regex);
它返回:
profile.php?id=1111,1111,profile.php?id=2222,2222,profile.php?id=33333,33333,
我想要的只是用户ID。难道我做错了什么?     
已邀请:
带g标志的string.match仅返回与完整正则表达式匹配的字符串。您想要捕获组,则需要使用RegExp.exec 像这样:
var text=\"lots of stuff with something in here a few times so that something comes back multiple times when searching for something.\";

var regex=new RegExp(\"some(thing)\",\"g\");

var result=null;

while(result=regex.exec(text)){
    document.write(result[1]);
}
您应该阅读正则表达式中的捕获组,以了解其工作原理。第一组始终是完整匹配,然后每个捕获组按顺序排列。     
.match()
方法不仅返回括号中的内容。它返回整个匹配模式 像这样做:
var regex = /profile\\.php\\?id=(\\d*)/g;
var matches = regex.exec(source);
matches[0]
将是整个比赛,而
matches[1,2,3 ... n]
将是括号中的捕获部分。     
这个jsfiddle可以满足您的需求: http://jsfiddle.net/city41/pm3rR/ 这是它的代码:
var source = \"profile.php?id=1111,1111,profile.php?id=2222,2222,profile.php?id=33333,33333,\";
var regex = /profile\\.php\\?id=(\\d*)/g;
var matches = regex.exec(source);

alert(matches[0]);
alert(matches[1]);
alert(regex.lastIndex);

matches = regex.exec(source);

alert(matches[0]);
alert(matches[1]);
alert(regex.lastIndex);
每当执行regex.exec(...)时,它都会在内部将其
lastIndex
属性设置为最后一个匹配项的最后一个索引。因此,如果再次执行该正则表达式,它将从上次停止的地方开始提取。 很明显,我的源字符串与您的源字符串不同,但是其中包含多个\“ id = ... \”,因此具有相同的效果。     

要回复问题请先登录注册