簡體   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