开发者

Replace urls with live links using C#

I have got a block of user text where I need to find all the web addresses and change them to hyperlinks. For eg in the following block I need to replace www.google.com with <a href="www.google.com">www.google.com</a> and www.yahoo.com with <a href="www.yahoo.com">www.yahoo.com</a>.

Lorem ipsum dolor sit www.google.com amet, consectetuer adipiscing elit, www.yahoo.com sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip

Do I have to split the string, and then match each word with a regular expression, and if match is found I replace? But I think there is a better approach to it, just that I am unable to figure it out.

Thanx for the help.

Devan开发者_JS百科g.


Regex.Replace will replace multiple occurrences of sub-strings that match a given pattern, so there is no need to split the string first.

The hard part is deciding what you want to match as a URL. For example, if you want to match any string that is compatible with RFC 3987, then your pattern is going to get quite complicated.

If your embedded URLs don't include the "http://" part, then it may be dificult to identify them, so the pattern you choose will depend upon the your input text.


string s = "Lorem ipsum dolor sit www.google.com amet, consectetuer adipiscing elit, www.yahoo.com sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip";

string newS = Regex.Replace(s, "((https?://)?www\\.[^\\s]+)", "<a href=\"$1\">$1</a>");

Console.WriteLine(newS);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜