user1952811
user1952811

Reputation: 2468

regex not being called repeatedly for multiple matches (isn't global)

I have this regex /@[a-zA-Z0-9_]+$/g to do a global look up of all user names that are mentioned.

Here is some sample code.

var userRegex = /@[a-zA-Z0-9_]+$/g;
var text = "This is some sample text @Stuff @Stuff2 @Stuff3";
text.replace(userRegex, function(match, text, urlId) {
    console.log(match);
});

So basically that console.log only gets called once, in this case it'll just show @Stuff3. I'm not sure why it isn't searching globally. If someone can help fix up that regex for me, that'd be awesome!

Upvotes: 0

Views: 30

Answers (3)

Kannan Mohan
Kannan Mohan

Reputation: 1850

Adding to @Oriol's answer. You can add word boundaries to be more specific.

@([a-zA-Z0-9_]+)\b

the \b will cause the username to match only if it is followed by a non-word character.

Here is the regex demo.

Upvotes: 0

hwnd
hwnd

Reputation: 70732

It isn't doing a global search throughout the entire context simply because of the end of string $ anchor (which only asserts at the end of string position). You can use the following here:

var results = text.match(/@\w+/g) //=> [ '@Stuff', '@Stuff2', '@Stuff3' ]

Note: \w is shorthand for matching any word character.

Upvotes: 2

Oriol
Oriol

Reputation: 288590

$ means "Assert the position at the end of the string (or before a line break at the end of the string, if any)". But you don't seem to want that.

So remove the $ and use /@[a-zA-Z0-9_]+/g instead.

var userRegex = /@[a-zA-Z0-9_]+/g,
    text = "This is some sample text @Stuff @Stuff2 @Stuff3";
text.match(userRegex); // [ "@Stuff", "@Stuff2", "@Stuff3" ]

Upvotes: 3

Related Questions