Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression: take string literally with special re-characters

Tags:

c#

regex

Maybe simple question..

String text = "fake 43 60 fake";
String patt = "[43.60]";

Match m = Regex.Match(text, patt)

In this situation, m.Success = true because the dot replace any character (also the space). But I must match the string literally in the patt.

Of course, I can use the '\' before the dot in the patt

String patt = @"[43\.60]";

So the m.Success = false, but there's more special characters in the Regular Expression-world.

My question is, how can I use regular expression that a string will be literally taken as it set. So '43.60' must be match with exactly '43.60'. '43?60' must be match with '43?60'....

thanks.

like image 688
robertpnl Avatar asked Aug 12 '11 09:08

robertpnl


1 Answers

To get a regex-safe literal:

string escaped = Regex.Escape(input);

For example, to match the literal [43.60]:

string escaped = Regex.Escape(@"[43.60]");

gives the string with content: \[43\.60].

You can then use this escaped content to create a regex; for example:

string find = "43?60";
string escaped = Regex.Escape(find);
bool match = Regex.IsMatch("abc 43?60", escaped);

Note that in many cases you will want to combine the escaped string with some other regex fragment to make a complete pattern.

like image 53
Marc Gravell Avatar answered Sep 30 '22 04:09

Marc Gravell