问题描述
我需要javascript正则表达式,以匹配不带空格字符且之前带有@的单词,例如:
I need javascript regex that will match words that are NOT followed by space character and has @ before, like this:
@bug-查找"@bug",因为之后没有空格
@bug - finds "@bug", because no space afer it
@bug和我-什么也找不到,因为"@bug"后有空格
@bug and me - finds nothing because there is space after "@bug"
@bug和@another-仅找到"@another"
@bug and @another - finds "@another" only
@bug和@another之类的东西-找不到任何东西,因为两个词都跟着空格.
@bug and @another and something - finds nothing because both words are followed by space.
有帮助吗?添加:从中获取字符串,并且FF在其末尾放置自己的标签.尽管我基本上只需要以@开头的最后一个单词,但是不能使用$(字符串的结尾).
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.
推荐答案
尝试re = /@\w+\b(?! )/
.这将查找一个单词(确保它捕获了整个单词),并使用否定的超前查询来确保单词后没有空格.
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.
使用上面的设置:
var re = /@\w+\b(?! )/, // etc etc
for ( var i=0; i<cases.length; i++ ) {
print( re2.exec(cases[i]) )
}
//prints
@bug
null
@another
null
这唯一不起作用的方法是,如果您的单词以下划线结尾,并且您希望标点符号成为单词的一部分:例如,由于@another
,'@ bug和@another_ blahblah'将选择@another后面没有空格.似乎不太可能,但是如果您也想处理这种情况,则可以使用/@\w+\b(?![\w ]/
,对于@bug and @another_
来说返回null
,对于@another and @bug_
则返回@bug_
.
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_
.
这篇关于Javascript正则表达式:找到一个单词NOT,后跟空格字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!