0

我有以下字符串,我必须从中提取用户名和 ID。

This is a string which has a @[User Full Name](contact:1)  data inside.

要从上面的字符串中获取用户名和联系人 ID,我正在使用这个正则表达式模式。

    var re = /\@\[(.*)\]\(contact\:(\d+)\)/;
    text = text.replace(re,"username:$1 with ID: $2");
// result == username: User Full Name with ID: 1

它现在完美运行的问题是我在字符串中有多个用户名,我尝试使用 /g (全局)但它没有正确替换:示例字符串:

This is a string which has a @[User Full Name](contact:1)  data inside. and it can also contain many other users data like  @[Second Username](contact:2) and  @[Third username](contact:3) and so many others....

当使用全局时,我得到这个结果:

var re = /\@\[(.*)\]\(contact\:(\d+)\)/g;
text = text.replace(re,"username:$1 with ID: $2");
//RESULT from above     
This is a string which has a user username; User Full Name](contact:1) data inside. and it can also contain many other users data like @[[Second Username](contact:2) and @[Third username and ID: 52 and so many others....
4

2 回答 2

2

您只需要?在第一个捕获组中进行非贪婪匹配。通过让.*你匹配尽可能多的数量,而如果你使用.*?,它匹配尽可能少的数量。

/@\[(.*?)\]\(contact:(\d+)\)/

如果联系这个词并不总是存在,你可以这样做..

/@\[(.*?)\]\([^:]+:(\d+)\)/

查看工作演示

于 2013-09-25T01:04:28.007 回答
0

不能说我可以看到您生成的字符串将如何可用。像这样的东西怎么样...

var re = /@\[(.*?)\]\(contact:(\d+)\)/g;
var users = [];
var match = re.exec(text);
while (match !== null) {
    users.push({
        username: match[1],
        id: match[2]
    });
    match = re.exec(text);
}
于 2013-09-25T01:10:48.700 回答