There are times when I want to convert user input into its literal value in a regular expression. I.e. if the user enters C:\Win\Bin\File.txt the regular expression would be something like C:\\Win\\Bin\File.txt since certain character combinations have to be escaped. Does anyone know of either a tried and true piece of code that does this, or some other technique that does this automatically?
-
"C:\Win\Bin\File.txt" and "C:\Win\Bin\File.txt" in your example.. what's the difference?Konstantin Tarkus– Konstantin Tarkus2009-04-10 07:06:49 +00:00Commented Apr 10, 2009 at 7:06
-
Converting symbolic characters to literal characters is called "escaping". What you need is to "escape" the user input so that it cannot contain any symbolic characters like the backslash. Depending on your technical environment, there's surely a built-in way to accomplish this.bzlm– bzlm2009-04-10 07:18:45 +00:00Commented Apr 10, 2009 at 7:18
Add a comment
|
1 Answer
Have you tried Regex.Escape()?
E.g.
var userInputRegex = new Regex(Regex.Escape(userInput));
3 Comments
bzlm
Yes, that would work for .NET; "This instructs the regular expression engine to interpret these characters literally rather than as metacharacters".
Waleed Eissa
+1 for the good answer, but why is everyone using vars these days?!
bzlm
Because their eyesight is good enough to be able to read the "new Regex" on the right. And because they want to make refactoring easier. And because they want their code to show more of the "what" and less of the "how" to increase readability. The question is, where have you been in the last years?