Replace urls with live links using C#

做~自己de王妃 提交于 2019-12-11 10:41:28

问题


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.

Devang.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6811590/replace-urls-with-live-links-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!