最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - regex for "mentions" - Stack Overflow

programmeradmin4浏览0评论

I'm struggling to e up with a regex that would find the ampersat in the beginning of words only. For example:

Here: The @dog went to the park.

But not here: The d@og went to the park.

Or here: The@dog went to the park.

Essentially, I just want to capture normal "mention" behavior, while omitting weird edge cases. I feel that this is mon enough that there must be some well-established regex for this.

Edit:

I tried with this:

/(@\w+)/gi

But, it captures cases that I do not wish to obtain.

I'm struggling to e up with a regex that would find the ampersat in the beginning of words only. For example:

Here: The @dog went to the park.

But not here: The d@og went to the park.

Or here: The@dog went to the park.

Essentially, I just want to capture normal "mention" behavior, while omitting weird edge cases. I feel that this is mon enough that there must be some well-established regex for this.

Edit:

I tried with this:

/(@\w+)/gi

But, it captures cases that I do not wish to obtain.

Share Improve this question edited Feb 2, 2016 at 20:47 Wiktor Stribiżew 627k41 gold badges496 silver badges611 bronze badges asked Feb 2, 2016 at 20:39 nmacnmac 6801 gold badge11 silver badges20 bronze badges 6
  • Please post your attempt. – Wiktor Stribiżew Commented Feb 2, 2016 at 20:40
  • That's an at-sign, ampersand is &. – Barmar Commented Feb 2, 2016 at 20:41
  • What language is this? – z7r1k3 Commented Feb 2, 2016 at 20:43
  • 1 Yes, its also called an 'ampersat', also, its javascript – nmac Commented Feb 2, 2016 at 20:43
  • 1 @nmac I never knew it was called an ampersat. Thanks for the education! – Gary_W Commented Feb 2, 2016 at 20:52
 |  Show 1 more ment

2 Answers 2

Reset to default 16

You may use the following regex:

/\B@\w+/g

\B matches at a non-word boundary, thus, it requires a non-word (or start of string) to be right before @.

See the 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>";

The regex should look something like this:

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

This will look for either @ at the beginning of the first word, or @ at the beginning of a word that follows.

发布评论

评论列表(0)

  1. 暂无评论