Reputation: 27342
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
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 @
.
Upvotes: 11
Reputation: 4795
Try using
(?<=^|\s)@\w+
Can't remember if c# allows alternation in a look behind
Upvotes: 1
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