Geuis
Geuis

Reputation: 42267

Prevent regex group from including previous character?

I'm attempting to get any words starting with @, such as in "@word", but only get the "word" value.

My sample text is:

@bob asodija qwwiq qwe @john @cat asdasd@qeqwe 

My current regex is:

/\B@(\w+)/gi

This works perfectly, except that "@" is still being captured. The output of this match is:

"@bob"
"@john"
"@cat"

I've tried setting the @ in a back reference, but its still including the @ in the results.

/\B(?:@)(\w+)/gi

Upvotes: 1

Views: 137

Answers (3)

meouw
meouw

Reputation: 42140

Here's a neat trick using the String.replace method, which can take a function as the replacement.

var matches = [];
var str = "@bob asodija qwwiq qwe @john @cat asdasd@qeqwe";

str.replace( /\B@(\w+)/g, function( all, firstCaptureGroup ) {
    matches.push( firstCaptureGroup );
});
console.log( matches ); //["bob", "john", "cat"]

Upvotes: 2

Gargolev
Gargolev

Reputation: 43

Here is a better solution without additional calculations except of regular expression:

(?<=\B@)(\w+)

Upvotes: -2

Paul
Paul

Reputation: 141839

You want to use the match array returned from exec

var teststr = '@bob asodija qwwiq qwe @john @cat asdasd@qeqwe';
var exp = /\B@(\w+)/gi;

var match = exp.exec(teststr);
while(match != null){
    alert(match[1]); // match 1 = 1st group captured
    match = exp.exec(teststr);
}

Upvotes: 5

Related Questions