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?
views:
126answers:
1
+3
A:
Have you tried Regex.Escape()?
E.g.
var userInputRegex = new Regex(Regex.Escape(userInput));
trendl
2009-04-10 07:16:16
Yes, that would work for .NET; "This instructs the regular expression engine to interpret these characters literally rather than as metacharacters".
bzlm
2009-04-10 07:17:38
+1 for the good answer, but why is everyone using vars these days?!
Waleed Eissa
2009-04-10 11:50:50
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?
bzlm
2009-04-13 14:05:29