正则表达式"提及"

时间:2016-02-02 20:39:36

标签: javascript regex

我努力想出一个只能在单词开头找到ampersat的正则表达式。例如:

此处:The @dog went to the park.

但不是在这里:The d@og went to the park.

或者在这里:The@dog went to the park.

基本上,我只想捕获正常的"提及"行为,同时省略奇怪的边缘情况。我觉得这很常见,必须有一些完善的正则表达式。

编辑:

我试过这个:

/(@\w+)/gi

但是,它捕获了我不想获得的案例。

2 个答案:

答案 0 :(得分:4)

您可以使用以下正则表达式:

/\B@\w+/g

\B匹配非字边界,因此,它要求非字(或字符串的开头)在@之前。

请参阅regex demo



var re = /\B@\w+/g; 
var str = 'The @dog went to the park.\nBut not here: The d@og went to the park.\nOr here: The@dog went to the park.';
var res = str.match(re);
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";
&#13;
&#13;
&#13;

答案 1 :(得分:0)

正则表达式看起来像这样:

^@[A-Za-z]+|.+ @[A-Za-z]+

这将在第一个单词的开头查找@,或在后面的单词的开头查找@