您好我有一些文字要在标签内显示。
“嘿@ronald和@tom我们这个周末去哪儿了”
我需要做的是将其更改为
“嗨www.domain.com/ronald和www.domain.com/tom我们这个周末去哪儿了”
现在我有了这个代码,有人离开了stackoverflow帮助我构建,但是我在下一步该怎么做了。
Regex regex = new Regex(@"@[\S]+");
MatchCollection matches = regex.Matches(strStatus);
foreach (Match match in matches)
{
string Username = match.ToString().Replace("@", "");
}
我无法在foreach中设置标签,因为它会忽略替换的最后一个单词,我希望我有意义。
答案 0 :(得分:1)
将您找到的用户名保留在列表中。从最长到最短迭代这些,用 www.domain.com/ [username] 替换每次出现的 @ [username] 。做最长到最短的原因是避免替换部分匹配,如“嘿,@ tom和@tomboy ......”这肯定不是最有效的替换方法(因为你做了一个完整的字符串扫描每个用户名,但是根据你的例子,我怀疑你的字符串很短,而且缺乏效率比这个机制的简单性要轻。
var usernames = new List<string>();
Regex regex = new Regex(@"@[\S]+");
MatchCollection matches = regex.Matches(strStatus);
foreach (Match match in matches)
{
usernames.Add( match.ToString().Replace("@", "") );
}
// do longest first to avoid partial matches
foreach (var username in usernames.OrderByDescending( n => n.Length ))
{
strStatus = strStatus.Replace( "@" + username, "www.domain.com/" + username );
}
如果你想构建实际的链接,它看起来像:
strStatus = strStatus.Replace( "@" + username,
string.Format( "<a href='http://www.domain.com/{0}'>@{0}</a>", username ) );
答案 1 :(得分:1)
string strStatus = "Hey @ronald and @tom where are we going this weekend";
Regex regex = new Regex(@"@[\S]+");
MatchCollection matches = regex.Matches(strStatus);
foreach (Match match in matches)
{
string Username = match.ToString().Replace("@", "");
strStatus = regex.Replace(strStatus, "www.domain.com/" + Username, 1);
}
}