0

I want to write a regular expression in C# so that the user can input a word he is looking for. For example: User writes in to a textBox in WPF the name of a movie. In C# I store that text input into a string variable.

How can I add that variable to a regular expression?

        string nameOfMovie = textBox.Text;
        string reg = @".*(nameOfMovie).*";

In the end I want to see all the movies in a List for example that contain the entered word.

P.s. I know it can be done a lot quicker with c# built in string functions but I want to use regular expressions.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
mrNobody
  • 91
  • 1
  • 1
  • 7
  • 2
    What's wrong with `string reg = ".*(" + nameOfMovie + ").*";`? (Or alternatively in C#6+, `string reg = $".*({nameOfMovie}).*";`) – Abion47 Mar 15 '17 at 01:14
  • what would be the input? – Akash KC Mar 15 '17 at 01:18
  • @Abion47 thank you soooo much :D – mrNobody Mar 15 '17 at 01:19
  • 2
    putting the user input directly into a regular expression introduces a regular expression vulnerability-- a malicious user can denial-of-service attack you by putting in a computationally difficult pattern. You should sanitize the input and build the regular expression with care to avoid this. – Tim Mar 15 '17 at 01:22
  • 1
    If you must use regular expressions you should also escape the name like this `string reg = ".*(" + Regex.Escape(nameOfMovie) + ").*";` in case the name contains any characters that have a special meaning for regular expressions (unless you want the user to be able to include regular expression syntax). – juharr Mar 15 '17 at 01:22

0 Answers0