简体   繁体   English

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

[英]Replace and delete with Regular expression?

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

The result is normal link (a href) and after that there is a string http://. 结果是普通链接(a href),然后是字符串http://。 How do I get only a link? 我如何仅获得链接?

Not clear exactly what are you trying to do. 不清楚您到底想做什么。 how does the input Result looks like. 输入Result如何。 if Result only contains the URL then just change: 如果Result仅包含URL,则只需更改:

Result = rgx.Replace(Result, replacement);

to

Result = replacement;

Update: 更新:

Anyway, You can use this function: 无论如何,您可以使用以下功能:

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");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM