Matt Wilko
Matt Wilko

Reputation: 27342

Regex to match mentions that begin with @

I am trying to develop some regex to find all words that start with an @:

I thought that \@\w+ would do it but this also matches words that have @ contained within them

e.g. @help me@ ple@se @now

matches at Index: 0 Length 5, Index: 13 Length 3, Index: 17 Length 4

This shouldn't match at Index 13 should it?

Upvotes: 5

Views: 9872

Answers (4)

falsetru
falsetru

Reputation: 369274

Use \B@\w+ (non-word boundary).

For example:

string pattern = @"\B@\w+";
foreach (var match in Regex.Matches(@"@help me@ ple@se @now", pattern))
    Console.WriteLine(match);

output:

@help
@now

BTW, you don't need to escape @.

http://ideone.com/nsT015

Upvotes: 11

OGHaza
OGHaza

Reputation: 4795

Try using

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

Can't remember if c# allows alternation in a look behind

RegExr

Upvotes: 1

user2480047
user2480047

Reputation:

And what about a non-Regex approach?

C# version:

string input = "word1 word2 @word3 ";
string[] resultWords = input.Split(' ').ToList().Where(x => x.Trim().StartsWith("@")).ToArray();

VB.NET version:

Dim input As String = "word1 word2 @word3 "
Dim resultWords() As String = input.Split(" "c).ToList().Where(Function(x) x.Trim().StartsWith("@")).ToArray

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063338

How about a negative look-behind:

(?<!\w)@\w+

Upvotes: 4

Related Questions