0

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?

2
  • "C:\Win\Bin\File.txt" and "C:\Win\Bin\File.txt" in your example.. what's the difference? Commented 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. Commented Apr 10, 2009 at 7:18

1 Answer 1

3

Have you tried Regex.Escape()?

E.g.

var userInputRegex = new Regex(Regex.Escape(userInput));
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, that would work for .NET; "This instructs the regular expression engine to interpret these characters literally rather than as metacharacters".
+1 for the good answer, but why is everyone using vars these days?!
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.