Question

I will use simple codes to describe my situation. For example, here are the codes:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(?!non)\w+\b";
      string input = "Nonsense is not always non-functional.";
      foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
         Console.WriteLine(match.Value);
   }
}

Now, I would like to replace the "non" with a user input. Let say it's called "UserInput" and the codes are written perfectly for getting the user input. I want to do like this, but error exists:

string pattern = @"\b(?!{0})\w+\b", UserInput;

Is there any way to replace the "non" inside the pattern of regex with user input?

Was it helpful?

Solution

I think you're just missing string.Format():

string pattern = string.Format(@"\b(?!{0})\w+\b", UserInput);

OTHER TIPS

To insert a string within another string you could use:

string userInput = "some text";
string originalText = @"\b(?!})\w+\b";
string newText = originalText.Insert(5, userInput);

There are 2 parts - inserting user's input in a string and making sure input actually will work inside regular expression.

Inserting can be easily done with string.Format or string interpolation if you are using C# 6.0+ (How do I interpolate strings?).

Now on second part - if user inputs "." and you blindly insert it into regular expression it will match all strings instead of just ".". To handle it correctly use Regex.Escape as shown in Escape Special Character in Regex.

So result:

  var pattern = String.Format(@"\b(?!{0})\w+\b", Regex.Escape(userInput));

Note that if userInput should actually contain regular expression (like "." should match any character) you should not escape the input, but it can lead to unbounded execution time as users can provide rogue regular expressions that take forever. Only consider it as an option in cases when all users are trusted to not try to break the system.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top