Reputation: 551
I am trying to construct a regular expression which parses mentions. e.g.
@aaa @bbb@ccc @dddd @eeee
it should match only aaa, dddd and eeee but not bbb@ccc
I have tried the following regular expression but it fails:
/(?:^|\s)@(\S+)/g
an example can be found here: https://regexr.com/3h9o5
Upvotes: 0
Views: 53
Reputation: 70
Your RE doesn't match because of \S. \S match @ too, so you need to replace it for what a name should be. Your RE should be something like
/(?:^|\s)@([^@\s]+)/g
Here it will match just 'aa' from '@aa@'. If you want whitespaces after the name you should use
/(?:^|\s)@([^@\s]+)(?=\s|$)/g
Upvotes: 1
Reputation: 785146
You can use this regex with \B
and negated character class:
\B@([^@\s]+)(?=\s|$)
RegEx Breakup:
\B
: assert position where \b
does not match[^@\s]+
: Match 1 or more characters that are not @
and not a whitespace(?=\s|$)
: Lookahead to assert that we have whitespace or end of line at next positionUpvotes: 2