[英]Make links clickable except when they already are using C#
我發現了一些使用正則表達式來檢測文本段落內URL的模式並添加HTML代碼以使其鏈接的示例。 我使用這種方法的問題是,有時輸入段落既包含以純文本形式編寫的URL(我希望將其轉換為可點擊的URL),也包含一些已經具有鏈接標記的URL。 例如,考慮以下段落:
My favourite search engine is http://www.google.com but
sometimes I also use <a href="http://www.yahoo.com">http://www.yahoo.com</a>
我只想轉換Google鏈接,但保留兩個Yahoo鏈接不變。
我所需要的是一個C#函數,該函數使用正則表達式來檢測URL並將其轉換,但會忽略URL,這些URL要么在其周圍帶有“ A”標記標簽,要么在其內部已經具有“ A”標記。
編輯
這是我到目前為止的內容:
PostBody = "My favourite search engine is http://www.google.com but sometimes I also use <a href=\"http://www.yahoo.com\">http://www.yahoo.com</a>";
String pattern = @"http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?";
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);
System.Text.RegularExpressions.MatchCollection matches = regex.Matches(PostBody);
for (int i = 0; i < matches.Count; i++)
{
PostBody = PostBody.Replace(matches[i].Value, String.Format("<a href=\"{0}\">{1}</a>", matches[i].Value, matches[i].Value));
}
ltrlPostBody.Text = PostBody;
這就是我得到的(為了清楚起見,我將其分成多行):
My favourite search engine is
<a href="http://www.google.com">http://www.google.com</a>
but sometimes I also use
<a href="<a href="<a href="http://www.yahoo.com">http://www.yahoo.com</a>">
<a href="http://www.yahoo.com">http://www.yahoo.com</a></a>">
我只想轉換第一個鏈接(在這種情況下),因為它尚未成為鏈接標記的一部分。
您還可以使用HTML Agility Pack ,它為您提供了更多功能(例如,您不想逃脫
<script></script>
元素和樣式元素:
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
namespace ConsoleApplication3 {
class Program {
static void Main(string[] args) {
var text = @"My favourite search engine is http://www.google.com but
sometimes I also use <a href=""http://www.yahoo.com"">http://www.yahoo.com</a>
<div>http://catchme.com</div>
<script>
var thisCanHurt = 'http://noescape.com';
</script>";
var doc = new HtmlDocument();
doc.LoadHtml(text);
var regex = new Regex(@"http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", RegexOptions.IgnoreCase);
var nodes = doc.DocumentNode.SelectNodes("//text()");
foreach (var node in nodes) {
if (node.ParentNode != null && (node.ParentNode.Name == "a" || node.ParentNode.Name == "script" || node.ParentNode.Name == "style")) {
continue;
}
node.InnerHtml = regex.Replace(node.InnerText, (match) => {
return string.Format(@"<a href=""{0}"">{0}</a>", match.Value);
});
}
var builder = new StringBuilder(100);
using (var writer = new StringWriter(builder)) {
doc.Save(writer);
}
var compose = builder.ToString();
}
}
}
如果您已經編寫了Regex來確定何時使用錨標記包裹文本,則可以通過http://msdn.microsoft.com/zh-cn/library/sdx2bds0使用RegularExpressions確定輸入是否匹配。 aspx
可以做一些簡單的事情
private string Pattern = "whateverregexpatternyouhavewritten";
private bool MatchesPattern(string input)
{
return Regex.IsMatch(Pattern, input);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.