简体   繁体   English

.NET RegEx有条件替换

[英].NET RegEx conditional replacement

I'm trying to convert text containing URL's into HTML anchors using Visual Basic in ASP.NET 2.0, so far I have this (which is working) but it only picks up http and https: 我正在尝试使用ASP.NET 2.0中的Visual Basic将包含URL的文本转换为HTML锚点,到目前为止,我已经做到了这一点(正在运行),但是它只能选择http和https:

Regex.Replace(message, "https?://[^\s]*", "<a href=""$0"">$0</a>", RegexOptions.IgnoreCase)

I would like it to be able to also pick up anything starting "www.", so I tried the following: 我希望它也可以提取以“ www。”开头的任何内容,因此我尝试了以下操作:

Regex.Replace(message, "(https?://|www\.)[^\s]*", "<a href=""$0"">$0</a>", RegexOptions.IgnoreCase)

However, if it starts with "www." 但是,如果以“ www。”开头。 the first $0 in the replacement requires an additional "http://" to be put in front... and I haven't got a clue how to do it (or if it's possible). 替换中的第一个$ 0需要在前面加上一个额外的“ http://” ...,但我不知道如何执行此操作(或者是否有可能)。

尝试这个:

Regex.Replace(message, "(?:http(s?)://|(www\.))([^\s]+)", "<a href=""http$1://$2$3"">http$1://$2$3</a>", RegexOptions.IgnoreCase)

UPDATE 更新

Convert text containing URL's into HTML anchors and insert http:// or https:// if it isn't in the input string : 将包含URL的文本转换为HTML锚,并在输入字符串中未插入http://或https://的情况下:

string input = "text www.stackoverflow.com/questions message";
string pattern = @"(http(?<ssl>s?)://|(?<www>www\.))(?<url>[^\s]*)";
string replacement = "<a href=\"http${ssl}://${www}${url}\">http${ssl}://${www}${url}</a>";

Console.WriteLine(Regex.Replace(input, pattern, replacement, RegexOptions.IgnoreCase));

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

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