【问题标题】:How to replace a user input in regular expression?如何替换正则表达式中的用户输入?
【发布时间】:2014-04-09 09:35:30
【问题描述】:

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

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

现在,我想用用户输入替换“非”。假设它被称为“UserInput”,并且代码是为获取用户输入而编写的。我想这样做,但存在错误:

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

有没有办法用用户输入替换正则表达式模式中的“非”?

【问题讨论】:

    标签: c# regex pattern-matching


    【解决方案1】:

    我认为你只是缺少string.Format()

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

    【讨论】:

    • 谢谢!现在我看到了我的问题。 =)
    • 警告您永远不要将用户输入直接放入正则表达式(导致类似于 SQL 注入的问题)
    【解决方案2】:

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

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

    【讨论】:

    • originalText.Insert();是的,这就是我要寻找的。感谢您的回答!
    【解决方案3】:

    有两部分 - 在字符串中插入用户的输入并确保输入实际上可以在正则表达式中工作。

    如果您使用的是 C# 6.0+ (How do I interpolate strings?),则可以使用 string.Format 或字符串插值轻松完成插入。

    现在在第二部分 - 如果用户输入“.”并且您盲目地将其插入到正则表达式中,它将匹配所有字符串而不仅仅是“.”。要正确处理它,请使用Regex.Escape,如Escape Special Character in Regex 所示。

    所以结果:

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

    请注意,如果userInput 实际上应该包含正则表达式(如“.”应该匹配任何字符),则不应转义输入,但它可能导致无限的执行时间,因为用户可以提供需要永远的恶意正则表达式。仅在所有用户都被信任不会尝试破坏系统的情况下才考虑使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2014-06-16
      • 2023-04-09
      • 2018-03-16
      相关资源
      最近更新 更多