我正在尝试匹配如下所示的字符串:
http://www.google.com
但如果它发生在像这样的更大的上下文中,则不会:
<a href="http://www.google.com"> http://www.google.com </a>
我得到的正则表达式在我测试过的几个不同的正则表达式引擎(PHP、ActionScript)中完成了这项工作,如下所示:
(?<!["'>]\b*)((https?://)([A-Za-z0-9_=%&@?./-]+))\b
你可以看到它在这里工作: http ://regexr.com?36g0e
问题是特定的 RegEx 在 .NET 下似乎无法正常工作。
private static readonly Regex fixHttp = new Regex(@"(?<![""'>]\b*)((https?://)([A-Za-z0-9_=%&@?./-]+))\b", RegexOptions.IgnoreCase);
private static readonly Regex fixWww = new Regex(@"(?<=[\s])\b((www\.)([A-Za-z0-9_=%&@?./-]+))\b", RegexOptions.IgnoreCase);
public static string FixUrls(this string s)
{
s = fixHttp.Replace(s, "<a href=\"$1\">$1</a>");
s = fixWww.Replace(s, "<a href=\"http://$1\">$1</a>");
return s;
}
具体来说,.NET 似乎并不关注第一个\b*
. 换句话说,它正确地无法匹配此字符串:
<a href="http://www.google.com">http://www.google.com</a>
但它错误地匹配了这个字符串(注意额外的空格):
<a href="http://www.google.com"> http://www.google.com </a>
关于我做错了什么或如何解决它的任何想法?