用于“提及"的正则表达式 [英] regex for "mentions"
问题描述
我正在努力提出一个正则表达式,该正则表达式只能在单词的开头找到安培符号.例如:
I'm struggling to come up with a regex that would find the ampersat in the beginning of words only. For example:
在这里: @dog去了公园.
但不在这里: d @ og去了公园.
或者在这里: The @ dog去公园了.
本质上,我只想捕获正常的提及"行为,而忽略怪异的边缘情况.我觉得这很常见,因此必须有一些完善的正则表达式.
Essentially, I just want to capture normal "mention" behavior, while omitting weird edge cases. I feel that this is common enough that there must be some well-established regex for this.
我尝试过:
/(@\w+)/gi
但是,它捕获了我不希望获得的案例.
But, it captures cases that I do not wish to obtain.
推荐答案
您可以使用以下正则表达式:
You may use the following regex:
/\B@\w+/g
\ B
在非单词边界匹配,因此,它要求在 @
之前的非单词(或字符串的开头).
\B
matches at a non-word boundary, thus, it requires a non-word (or start of string) to be right before @
.
请参见 regex演示
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>";
这篇关于用于“提及"的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!