【问题标题】:c# regex.ismatch using a variablec# regex.ismatch 使用变量
【发布时间】:2013-01-04 09:28:41
【问题描述】:

我有以下代码可以正常工作,但我需要用变量替换站点地址...

string url = HttpContext.Current.Request.Url.AbsoluteUri;  // Get the URL

bool match = Regex.IsMatch(url, @"(^|\s)http://www.mywebsite.co.uk/index.aspx(\s|$)");

我尝试了以下方法,但它不起作用,有什么想法吗???

string url = HttpContext.Current.Request.Url.AbsoluteUri;  // Get the URL
string myurl = "http://www.mywebsite.co.uk/index.aspx";

bool match = Regex.IsMatch(url, @"(^|\s)"+myurl+"(\s|$)");

【问题讨论】:

  • 错误信息是什么?
  • 到底是什么问题?当你将它作为变量传递时它只是不匹配还是抛出异常?
  • 错误在 \s 附近,我设法通过转义修复它:\\s
  • @Scott 看看 Mark Byers 的回答。

标签: c# regex


【解决方案1】:

您缺少@

bool match = Regex.IsMatch(url, @"(^|\s)" + myurl + @"(\s|$)");

您需要额外的@ 的原因是@ 仅适用于紧随其后的字符串文字。它不适用于该行的整个其余部分。

您还应该考虑escaping 您的网址:

bool match = Regex.IsMatch(url, @"(^|\s)" + Regex.Escape(myurl) + @"(\s|$)");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    相关资源
    最近更新 更多