在JavaScript Regex中替换所有内容

时间:2013-09-25 00:51:55

标签: javascript regex

我有以下字符串,我必须从中提取用户名和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....

2 个答案:

答案 0 :(得分:2)

您只需要在第一个捕获组中进行非贪婪的?匹配。如果您使用.*,则.*?匹配的金额最多,则匹配的金额最少。

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

如果单词 contact 并不总是存在,那么你可以做..

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

请参阅working demo

答案 1 :(得分: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);
}