用正则表达式替换和删除?

时间:2011-06-20 09:01:47

标签: c# parsing

if (Result.Contains("http://"))
{
  string pattern = @"(http://)";
  theend = Result.Substring(Result.IndexOf("http://"));
  Regex rgx = new Regex(pattern);
  string replacement = "<a href="+theend+">"+theend+"</a> ";
  Result = rgx.Replace(Result, replacement);
}

结果是普通链接(一个href),之后有一个字符串http://。我如何只获得一个链接?

1 个答案:

答案 0 :(得分:1)

不清楚你到底想要做什么。输入Result如何显示。 如果Result仅包含该网址,则只需更改:

Result = rgx.Replace(Result, replacement);

Result = replacement;

更新

无论如何,您可以使用此功能:

private string ConvertUrlsToLinks(string msg) {
        string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
        Regex r = new Regex(regex, RegexOptions.IgnoreCase);
        return r.Replace(msg, "<a href=\"$1\">$1</a>").Replace("href=\"www", "href=\"http://www");
    }