Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何替换正则表达式中的用户输入?_C#_Regex_Pattern Matching - Fatal编程技术网

C# 如何替换正则表达式中的用户输入?

C# 如何替换正则表达式中的用户输入?,c#,regex,pattern-matching,C#,Regex,Pattern Matching,我将使用简单的代码来描述我的情况。 例如,以下是代码: 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."; f

我将使用简单的代码来描述我的情况。 例如,以下是代码:

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);
   }
}
现在,我想用用户输入替换non。假设它被称为UserInput,代码编写得非常完美,可以获得用户输入。我想这样做,但存在错误:

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

有没有办法用用户输入来替换regex模式中的non


要在另一个字符串中插入字符串,可以使用:

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

有两个部分-在字符串中插入用户输入,并确保输入在正则表达式中实际工作

如果您使用的是C 6.0+,则可以使用string.Format或string插值轻松完成插入

现在进入第二部分-如果用户输入。然后盲目地将其插入正则表达式中,它将匹配所有字符串,而不仅仅是。。要正确处理,请按中所示使用

因此,结果:

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

注意,如果userInput实际上应该包含正则表达式,比如。如果与任何字符匹配,则不应转义输入,但这可能会导致无限的执行时间,因为用户可以提供耗时的恶意正则表达式。在所有用户都被信任不要试图破坏系统的情况下,只考虑它是一个选项。现在我明白我的问题了=警告:永远不要将用户输入直接放入正则表达式,这样会导致类似于SQL injectionoriginalText.Insert的问题;是的,这就是我要寻找的。谢谢你的回答!
  var pattern = String.Format(@"\b(?!{0})\w+\b", Regex.Escape(userInput));