简体   繁体   English

使用C#将URL替换为实时链接

[英]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> . 例如,在下面的方框中,我需要将www.google.com替换为<a href="www.google.com">www.google.com</a>并将www.yahoo.com替换为<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. Lorem ipsum dolor坐在www.google.com,信奉高尚,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 Ut wisi enim ad minim veniam,quis nostrud exulciation 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. 德文

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

Regex.Replace will replace multiple occurrences of sub-strings that match a given pattern, so there is no need to split the string first. Regex.Replace将替换多次出现的与给定模式匹配的子字符串,因此无需先拆分字符串。

The hard part is deciding what you want to match as a URL. 困难的部分是确定要匹配的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. 例如,如果您要匹配与RFC 3987兼容的任何字符串,那么您的模式将变得非常复杂。

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. 如果您的嵌入式URL不包含“ http://”部分,则可能很难识别它们,因此您选择的模式将取决于您的输入文本。

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

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