JohnnyM
JohnnyM

Reputation: 29566

Code to turn user input into a literal regular expression? (C#)

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?

Upvotes: 0

Views: 501

Answers (1)

trendl
trendl

Reputation: 1147

Have you tried Regex.Escape()?

E.g.

var userInputRegex = new Regex(Regex.Escape(userInput));

Upvotes: 3

Related Questions