我需要javascript正则表达式,它将匹配空格字符后面没有字符并且前面有@的单词,如下所示:
@bug - 找到“@bug”,因为没有空格
@bug和我 - 找不到任何东西,因为“@bug”之后有空格
@bug和@another - 仅发现“@another”
@bug和@another以及其他东西 - 找不到任何东西,因为这两个单词后跟空格。
帮助? 添加: 从中获取字符串,FF在其末尾放置自己的标记。虽然我基本上只需要以@开头的最后一个单词,但是$(结束字符串)不能使用。
答案 0 :(得分:12)
试试re = /@\w+\b(?! )/
。这会查找一个单词(确保它捕获整个单词)并使用否定前瞻来确保单词后面没有空格。
使用上面的设置:
var re = /@\w+\b(?! )/, // etc etc
for ( var i=0; i<cases.length; i++ ) {
print( re2.exec(cases[i]) )
}
//prints
@bug
null
@another
null
这不起作用的唯一方法是,如果你的单词以下划线结尾,并且你希望标点符号成为单词的一部分:例如'@bug和@another_ blahblah'将挑选@another自{{1没有后跟空格。
这似乎不太可能,但如果您也想处理这种情况,可以使用@another
,这将/@\w+\b(?![\w ]/
null
和@bug and @another_
@bug_
1}}。
答案 1 :(得分:5)
听起来你真的只是在输入结尾处寻找单词:
/@\w+$/
试验:
var re = /@\w+$/,
cases = ['@bug',
'@bug and me',
'@bug and @another',
'@bug and @another and something'];
for (var i=0; i<cases.length; i++)
{
console.log(cases[i], ':', re.test(cases[i]), re.exec(cases[i]));
}
// prints
@bug : true ["@bug"]
@bug and me : false null
@bug and @another : true ["@another"]
@bug and @another and something : false null