robertpnl
robertpnl

Reputation: 704

Regular expression: take string literally with special re-characters

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.

Upvotes: 5

Views: 2730

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063619

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.

Upvotes: 14

Related Questions