[英]Regex to match word beginning 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 我以为
\\@\\w+
可以做到,但这也可以匹配其中包含@的单词
eg @help me@ ple@se @now
例如
@help me@ ple@se @now
matches at Index: 0 Length 5, Index: 13 Length 3, Index: 17 Length 4
匹配
Index: 0 Length 5, Index: 13 Length 3, Index: 17 Length 4
This shouldn't match at Index 13 should it? 这不应该与索引13相匹配吗?
Use \\B@\\w+
(non-word boundary). 使用
\\B@\\w+
(非单词边界)。
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 @
. 顺便说一句,您不需要转义
@
。
否定性回望如何:
(?<!\w)@\w+
And what about a non-Regex approach? 非正则表达式方法又如何呢?
C# version: C#版本:
string input = "word1 word2 @word3 ";
string[] resultWords = input.Split(' ').ToList().Where(x => x.Trim().StartsWith("@")).ToArray();
VB.NET version: VB.NET版本:
Dim input As String = "word1 word2 @word3 "
Dim resultWords() As String = input.Split(" "c).ToList().Where(Function(x) x.Trim().StartsWith("@")).ToArray
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.