Javascript正则表达式:找到一个单词后跟空格字符

Zel*_*jko 3 javascript regex negative-lookbehind negative-lookahead

我需要javascript正则表达式,它将匹配空格字符后面没有字符并且前面有@的单词,如下所示:

@bug - 找到"@bug",因为它没有空间

@bug和我 - 因为"@bug"之后有空格而一无所获

@bug和@another - 只找到"@another"

@bug和@another等等 - 找不到任何东西,因为这两个单词后跟空格.

救命?补充:从中获取字符串,FF在其末尾放置自己的标记.虽然我基本上只需要以@开头的最后一个单词,但是$(结束字符串)不能使用.

mat*_*fee 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
Run Code Online (Sandbox Code Playgroud)

唯一不行的方法是,如果你的单词以下划线结尾,你希望标点符号成为单词的一部分:例如'@bug和@another_ blahblah'会选择@another,因为@another之后没有空间.这似乎不太可能,但如果你想处理那种情况下,你可以使用/@\w+\b(?![\w ]/,并且将返回null@bug and @another_@bug_@another and @bug_.


Mat*_*all 5

听起来你真的只是在输入结束时寻找单词:

/@\w+$/
Run Code Online (Sandbox Code Playgroud)

测试:

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
Run Code Online (Sandbox Code Playgroud)