[英]Javascript regex: find a word NOT followed by space character
我需要javascript正则表达式,它将匹配空格字符后面没有字符并且前面有@的单词,如下所示:
@bug - 找到“@bug”,因为它没有空间
@bug和我 - 因为“@bug”之后有空格而一无所获
@bug和@another - 只找到“@another”
@bug和@another等等 - 找不到任何东西,因为这两个单词后跟空格。
救命? 补充:从中获取字符串,FF在其末尾放置自己的标记。 虽然我基本上只需要以@开头的最后一个单词,但是$(结束字符串)不能使用。
尝试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,因为@another
没有被跟踪一个空间。 这似乎不太可能,但如果你也想处理那个案例,你可以使用/@\\w+\\b(?![\\w ]/
并且这将为@bug and @another_
和@bug_
@bug and @another_
返回null
@another and @bug_
。
听起来你真的只是在输入结束时寻找单词:
/@\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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.