[英]Replace all in 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....
你只需要一個不貪心的人?
匹配您的第一個捕獲組。 通過讓.*
而如果你使用的配套最可能的量.*?
,它匹配的可能性最小。
/@\[(.*?)\]\(contact:(\d+)\)/
如果聯系這個詞並不總是存在,你可以做..
/@\[(.*?)\]\([^:]+:(\d+)\)/
看工作演示
不能說我可以看到你的結果字符串是如何可用的。 這樣的事情怎么樣......
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.