繁体   English   中英

.NET RegEx有条件替换

[英].NET RegEx conditional replacement

我正在尝试使用ASP.NET 2.0中的Visual Basic将包含URL的文本转换为HTML锚点,到目前为止,我已经做到了这一点(正在运行),但是它只能选择http和https:

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

我希望它也可以提取以“ www。”开头的任何内容,因此我尝试了以下操作:

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

但是,如果以“ www。”开头。 替换中的第一个$ 0需要在前面加上一个额外的“ http://” ...,但我不知道如何执行此操作(或者是否有可能)。

尝试这个:

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

更新

将包含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