我正在尝试开发一些正则表达式来查找以@:
开头的所有单词我认为\@\w+
会这样做,但这也会匹配包含在其中的@的单词
e.g。
@help me@ ple@se @now
匹配Index: 0 Length 5, Index: 13 Length 3, Index: 17 Length 4
这应该与索引13不匹配吗?
答案 0 :(得分:5)
使用\B@\w+
(非字边界)。
例如:
string pattern = @"\B@\w+";
foreach (var match in Regex.Matches(@"@help me@ ple@se @now", pattern))
Console.WriteLine(match);
输出:
@help
@now
顺便说一句,你不需要逃避@
。
答案 1 :(得分:2)
负面观察如何:
(?<!\w)@\w+
答案 2 :(得分:2)
那么非正则表达式方法呢?
C#版本:
string input = "word1 word2 @word3 ";
string[] resultWords = input.Split(' ').ToList().Where(x => x.Trim().StartsWith("@")).ToArray();
VB.NET版本:
Dim input As String = "word1 word2 @word3 "
Dim resultWords() As String = input.Split(" "c).ToList().Where(Function(x) x.Trim().StartsWith("@")).ToArray
答案 3 :(得分:1)