c#regex.ismatch使用变量

Sco*_*ott 4 c#

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

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

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

我尝试了以下但它不起作用,任何想法???

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|$)");
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 10

你错过了一个@:

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

您需要额外的原因@是因为它@仅适用于紧随其后的字符串文字.它不适用于整个生产线的其余部分.

您还应该考虑转义您的网址:

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