使用C#替换带有实时链接的URL [英] Replace urls with live links using C#

查看:222
本文介绍了使用C#替换带有实时链接的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户文本块,我需要找到所有的网址并将其更改为超链接。例如,在下面的块中,我需要用< a href =www.google.com> www.google.com< / a> 和www.yahoo.com,< a href =www.yahoo.com> www.yahoo.com< / a>

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坐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

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的帮助。

Devang。

推荐答案

Regex.Replace 将替换多个匹配给定模式的子字符串,因此不需要先拆分字符串。

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

困难的部分是决定要匹配的内容一个URL。例如,如果要匹配与 RFC 3987 兼容的任何字符串,那么你的模式会变得非常复杂。

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.

如果你的嵌入式URL不包含http://部分,那么识别它们可能很困难,因此您选择的模式将取决于您的输入文本。

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.

这篇关于使用C#替换带有实时链接的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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