Javascript regex: find a word NOT followed by space character

Zeljko picture Zeljko · Dec 21, 2011 · Viewed 7.9k times · Source

I need javascript regex that will match words that are NOT followed by space character and has @ before, like this:

@bug - finds "@bug", because no space afer it

@bug and me - finds nothing because there is space after "@bug"

@bug and @another - finds "@another" only

@bug and @another and something - finds nothing because both words are followed by space.

Help? Added: string is fetched from and FF puts it's own tags at end of it. Although I basically need only the last word starting with @, $ (end-of-string) can not be used.

Answer

mathematical.coffee picture mathematical.coffee · Dec 21, 2011

Try re = /@\w+\b(?! )/. This looks for a word (making sure it captures the whole word) and uses a negative lookahead to make sure the word is not followed by a space.

Using the setup above:

var re = /@\w+\b(?! )/, // etc etc

for ( var i=0; i<cases.length; i++ ) {
    print( re2.exec(cases[i]) )
}

//prints
@bug
null
@another
null

The only way this won't work is if your word ends in an underscore and you wanted that punctuation to be part of the word: For example '@bug and @another_ blahblah' will pick out @another since @another wasn't followed by a space. This doesn't seem very likely but if you wanted to deal with that case too, you could use /@\w+\b(?![\w ]/ and that would return null for @bug and @another_ and @bug_ for @another and @bug_.