如何获得所有标记用户的循环

时间:2017-10-11 14:24:23

标签: c# asp.net loops

我试图从ASP.NET中的String获取所有标记的用户 例如,字符串“你好我的名字是@Naveh而我的朋友被命名为@Amit”,我希望它能以一种方式返回给我“Naveh”和“Amit”,我可以向每个用户发送一个通知方法,比如循环代码背后。

我知道捕获这些字符串的唯一方法是使用'替换'方法:(但这只适用于编辑当然)

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

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

2 个答案:

答案 0 :(得分:2)

您应该使用Regex.Match。

Regex.Match

E.g。

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();

答案 1 :(得分:0)

您可以使用Regex.Matches获取MatchCollection对象并使用foreach来抢夺它。 MSDN