Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# regex.ismatch using a variable

Tags:

c#

regex

I have the following code which works fine but i need to replace the site address with a variable...

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

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

I have tried the following but it doesn't work, any ideas???

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|$)");
like image 332
Scott Avatar asked Jan 21 '13 10:01

Scott


People also ask

What is C in simple words?

C Introduction C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is %d in C programming?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.


1 Answers

You are missing a @:

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

The reason that you need the extra @ is because the @ applies only to the string literal immediately following it. It does not apply to the entire rest of the line.

You should also consider escaping your URL:

bool match = Regex.IsMatch(url, @"(^|\s)" + Regex.Escape(myurl) + @"(\s|$)");
like image 161
Mark Byers Avatar answered Oct 22 '22 16:10

Mark Byers