Reputation: 192
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
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
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
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
Reputation: 785146
You can use following regular expression:
/(?:^|\W)@[\w]+(?:\s|$)/
Upvotes: 1