0

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

1

2 Answers 2

2

You can use this regex with \B and negated character class:

\B@([^@\s]+)(?=\s|$)

RegEx Demo

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 position
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks it works. But I am still not sure how \B works
I checked the pattern again. It fails here: regex101.com/r/7UH5K7/1
You can use: (?:^|\s)@([^@\s]+)(?=\s|$)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.