5

I want to match all strings that start with an @ unless they have other characters in front of the @ as well. Simple example: in @one @two and bla@three I want to match @one and @two but not @three. It's for highlighting usernames in a chatroom.

These strings can be anywhere in a sentence (right at the start or in the middle).

I actually thought that (?![a-zA-Z])@[a-zA-Z]+ should work but it still matches @three too.

10
  • 4
    You want negative lookbehind, not negative lookahead. But JS doesn't have that. See stackoverflow.com/questions/641407/… for a workaround. Commented Apr 10, 2014 at 22:13
  • 2
    So, essentially you're looking for a pattern that matches an "@something" which has a space in front? Or in other words: what characters other than a space should be allowed in front of the "@"? Commented Apr 10, 2014 at 22:13
  • 4
    /(?:^| )(@\S+)/ should do just fine. Or @[a-z]+, if there can be something else used as separator than ` `. Commented Apr 10, 2014 at 22:15
  • 1
    That would be /(^| )@[a-z]+/ig then... :) Commented Apr 10, 2014 at 22:15
  • 1
    @raina77ow Looks like you nailed it :) regex101.com/r/gE5cE4 Commented Apr 10, 2014 at 22:23

1 Answer 1

5

You don't need a regex look around, you can use a simple regex like this:

\B@\w+

Working demo

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

As an additional example: regexr.com/3apif on the RegExr site if you go to reference on the left, then anchors it'll explain \b RegExr is my go to for creating RegEx as the reference guides are right there without being in the way.
@MicTech you could use (?<=^| )@\w+
@FedericoPiazza JavaScript doesn't support that.
@MicTech true, forgot about that. Anyway, this question was posted 1 year ago and also marked as resolved, so guess it solved OP problem.

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.