【发布时间】:2013-11-29 09:34:20
【问题描述】:
我正在尝试开发一些正则表达式来查找所有以@开头的单词:
我认为\@\w+ 会这样做,但这也匹配其中包含@ 的单词
例如
@help me@ ple@se @now
匹配Index: 0 Length 5, Index: 13 Length 3, Index: 17 Length 4
这不应该在索引 13 处匹配吗?
【问题讨论】:
我正在尝试开发一些正则表达式来查找所有以@开头的单词:
我认为\@\w+ 会这样做,但这也匹配其中包含@ 的单词
例如
@help me@ ple@se @now
匹配Index: 0 Length 5, Index: 13 Length 3, Index: 17 Length 4
这不应该在索引 13 处匹配吗?
【问题讨论】:
使用\B@\w+(非单词边界)。
例如:
string pattern = @"\B@\w+";
foreach (var match in Regex.Matches(@"@help me@ ple@se @now", pattern))
Console.WriteLine(match);
输出:
@help
@now
顺便说一句,你不需要转义@。
【讨论】:
@。这没什么区别。 :)
消极的后视怎么样:
(?<!\w)@\w+
【讨论】:
Index: 0 Length 5, Index: 13 Length 3
那么非正则表达式方法呢?
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
【讨论】:
【讨论】: