查找网址的纯文本和HTML插入一个标记 [英] Find url in plain text and insert HTML A markups

查看:134
本文介绍了查找网址的纯文本和HTML插入一个标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有URL文本,我需要用HTML来包装他们的标记,该怎么做,在C#?



例如,我有



 我的文字和网址http://www.google.com结束。 



我想获得

 我的文字和网址< A HREF =htt​​p://www.google.com> HTTP://www.google.com< / A>结束。 


解决方案

您可以使用正则表达式这一点。如果你需要一个更好的正则表达式,你可以搜索在这里 http://regexlib.com/Search.aspx?k=url



我对这个快速的解决办法是这样的:

 串了mystring =我的文字和网址http://www.google.com结束。 

正则表达式urlRx =新的正则表达式(@(小于网址>(HTTP:[/] [/] | WWW)(即[az] | [AZ] | [0-9] |。 [/.]|[~])*),RegexOptions.IgnoreCase);

MatchCollection匹配= urlRx.Matches(myString的);

的foreach(赛的比赛在比赛中)
{
VAR URL = match.Groups [网址]值。
了mystring = mystring.Replace(网址,的String.Format(&下; A HREF = \{0} \> {0}&下; / A>中,链接));
}


I have text with URL and I need to wrap them with HTML A markup, how to do that in c#?

Example, I have

My text and url http://www.google.com The end.

I would like to get

My text and url <a href="http://www.google.com">http://www.google.com</a> The end.

解决方案

You can use a regex for this. If you need a better Regex you can search for it here http://regexlib.com/Search.aspx?k=url

My quick solution for this would be this:

string mystring = "My text and url http://www.google.com The end.";

Regex urlRx = new Regex(@"(?<url>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", RegexOptions.IgnoreCase);

MatchCollection matches = urlRx.Matches(mystring);

foreach (Match match in matches)
{
    var url = match.Groups["url"].Value;
    mystring = mystring.Replace(url, string.Format("<a href=\"{0}\">{0}</a>", url));
}

这篇关于查找网址的纯文本和HTML插入一个标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆