0

i have below string from which I have to extract username and ID.

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

To get username and contact id from above string I am using this regex pattern.

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

It works perfectly now issue is I have multiple usernames in string, I tried using /g (global) but its not replacing properly: Example string:

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....

when used global I get this result:

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 Answers 2

2

You just need a non greedy ? match in your first capture group. By having .* you are matching the most amount possible while if you use .*?, it matches the least amount possible.

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

And if the word contact is not always there, you could do..

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

See working demo

Sign up to request clarification or add additional context in comments.

1 Comment

Why are you escaping @?
0

Can't say I can see how your resulting string is going to be usable. How about something like this...

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);
}

1 Comment

Thank you Phil... informative but actually I am parsing that string data from database to view for user so there is no use of it at this point.... :) Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.