我有一个用户文本块,我需要找到所有的网址并将其更改为超链接。例如,在下面的块中,我需要用< a href =www.google> www.google< / a> 和www.yahoo,< a href =www.yahoo> www.yahoo< / 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 with <a href="www.google">www.google</a> and www.yahoo with <a href="www.yahoo">www.yahoo</a>.
Lorem ipsum dolor坐www.google amet,consectetuer adipiscing elit,www.yahoo 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 amet, consectetuer adipiscing elit, www.yahoo 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 "" part, then it may be dificult to identify them, so the pattern you choose will depend upon the your input text.
更多推荐
使用C#替换带有实时链接的URL
发布评论