2017-10-11 38 views
0

我想从ASP.NET中的字符串获取所有标记的用户 例如,字符串“你好,我的名字是@Naveh,我的朋友名为@Amit”,我会喜欢它以我可以向每个用户发送通知方法的方式返回“Naveh”和“Amit”,就像后面的代码循环一样。如何获得所有标记用户的循环

我知道赶上这些字符串的唯一方法是通过这样的“替换”的方法:(不过,这只是对当然是好的编辑)

Regex.Replace(comment, @"@([\S]+)", @"<a href=""../sellingProfile.aspx?name=$1""><b>$1</b></a>") 

你不能循环那些字符串像。我如何循环代码中的所有标记用户?

回答

2

你应该使用Regex.Match。

Regex.Match

例如,

string pat = @"@([a-z]+)"; 
string src = "Hello my name is @Naveh and my friend is named @Amit"; 

string output = ""; 

// Instantiate the regular expression object. 
Regex r = new Regex(pat, RegexOptions.IgnoreCase); 

// Match the regular expression pattern against a text string. 
Match m = r.Match(src); 

while (m.Success) 
{ 
    string matchValue = m.Groups[1].Value; //m.Groups[0] = "@Name". m.Groups[1] = "Name" 
    output += "Match: " + matchValue + "\r\n"; 
    m = m.NextMatch(); 
} 

Console.WriteLine(output); 
Console.ReadLine(); 
+0

谢谢,它的工作很棒。 – Naveh

0

您可以使用Regex.Matches通过foreach获取MatchCollection对象和掠夺。 MSDN