Ashraf ElSwify
Ashraf ElSwify

Reputation: 192

Regex: How to match all occurrences of @something in a string

I need to find all occurences of a word prededed by the '@' character in this way: @soemthing.

example:

string input = "@alias1 is my first email but @alias2.com and email@alias3 along with @alias4 are disabled"

I only want to match @alias1 and @alias4 but not @alias.com, or email@alias3

Thanks

Upvotes: 1

Views: 4474

Answers (5)

Peter O.
Peter O.

Reputation: 32878

Use the following: \b@\w+\b

You didn't specify programming language, so I'm assuming C#. I don't know however whether C# supports "\b".

EDIT:

I will adopt Justin's comment and suggest \B@\w+(?=["'\s]|$) instead.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425033

I would use this: (?<=(^|\s))@[a-zA-Z]+(?=(\s|$))

This regex says "@ followed by letters, but preceded by whitespace or start of line, and the next character is whitespace or end of line".

Although your example doesn't specify, if you are willing to accept underscore chars, eg @some_thing, then you can replace [a-zA-Z] with simply \w

Upvotes: 1

Steve Wortham
Steve Wortham

Reputation: 22220

This should work...

(?<=^|\s)@\w+(?=\s|$)

To explain, (?<=^|\s) is a positive lookbehind ensuring that you're either at the beginning of the string, or there's a character of whitespace preceding your match. And then (?=\s|$) is a positive lookahead ensuring that the match is followed by either by whitespace, or the end of the string.

Upvotes: 4

The Mask
The Mask

Reputation: 17427

Try with this regular expression:

@\w+

Upvotes: -2

anubhava
anubhava

Reputation: 785146

You can use following regular expression:

/(?:^|\W)@[\w]+(?:\s|$)/

Upvotes: 1

Related Questions