.NET RegEx条件替换

时间:2012-02-25 16:34:51

标签: .net regex

我试图在ASP.NET 2.0中使用Visual Basic将包含URL的文本转换为HTML锚点,到目前为止,我已经有了这个(这是有效的),但它只选择了http和https:< / p>

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

我希望它能够选择任何开始&#34; www。&#34;,所以我尝试了以下内容:

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

但是,如果它以&#34; www。&#34;开头。替换中的第一个$ 0需要额外的&#34; http://&#34;被放在前面......我还没有得到如何做到的线索(或者如果可能的话)。

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

更新

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