【问题标题】:c# Can't match Html Special charactersc#不能匹配Html特殊字符
【发布时间】:2016-11-13 03:40:48
【问题描述】:

我必须匹配 2 个 url,第一个来自 MySQL db,第二个来自 Html 页面。如果我将两者都作为字符串进行比较

var match = Regex.Match(href.Attributes["href"].Value, testString, RegexOptions.IgnoreCase);

match.Success = false. 两个字符串都类似于this : myUrl/rollcontainer-weiß,但 match.Success 仍然为 false。

我尝试添加HttpUtility.HtmlEncode 来检查两个字符串,我得到:myUrl/rollcontainer-wei&#233 用于第一个,myUrl/rollcontainer-wei&ß 用于第二个。

在这种情况下,我怎样才能拥有match.Success = true

【问题讨论】:

  • 这个answer怎么样?
  • 当我使用 Uri.Compare 时得到 -1
  • 试试var match = Regex.Match(href.Attributes["href"].Value, Regex.Escape(HttpUtility.HtmlDecode(testString)), RegexOptions.IgnoreCase);
  • 你的第二个是双重编码的!

标签: c# html mysql regex encode


【解决方案1】:

例如,试试这个功能。

static void Main(string[] args)
{
    bool test = Test("http://myUrl.com/rollcontainer-Wei&ß", "http://myUrl.com/rollcontainer-wei&ß");

}

public static bool Test(string url1, string url2)
{
    Uri uri1 = new Uri(HttpUtility.HtmlDecode(url1)); 
    Uri uri2 = new Uri(HttpUtility.HtmlDecode(url2));

    var result = Uri.Compare(uri1, uri2,
        UriComponents.Host | UriComponents.PathAndQuery,
        UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase);

    return result == 0;
}

【讨论】:

  • 酷!有用!我试过了,但 Uri 中没有 HtmlDecode !
  • 仅供参考 还有WebUtility.HtmlDecodeSystem.Net)。自 .Net 4.0 起可用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多