How to replace a user input in regular expression?

前提是你 提交于 2019-12-31 05:58:17

问题


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?


回答1:


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

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



回答2:


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);



回答3:


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.



来源:https://stackoverflow.com/questions/22958434/how-to-replace-a-user-input-in-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!