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.Format()
:
要在另一个字符串中插入字符串,可以使用:
string userInput = "some text";
string originalText = @"\b(?!})\w+\b";
string newText = originalText.Insert(5, userInput);
有两个部分-在字符串中插入用户输入,并确保输入在正则表达式中实际工作 使用
string.Format
或字符串插值(如果您使用的是C#6.0+())可以轻松完成插入
现在来看第二部分——如果用户输入“.”并盲目地将其插入正则表达式中,它将匹配所有字符串,而不仅仅是“.”。要正确处理,请按中所示使用
因此,结果:
var pattern = String.Format(@"\b(?!{0})\w+\b", Regex.Escape(userInput));
请注意,如果
userInput
实际上应该包含正则表达式(如“.”应该匹配任何字符),则不应该转义输入,但它可能会导致无限的执行时间,因为用户可以提供耗时的恶意正则表达式。在所有用户都被信任不要试图破坏系统的情况下,只考虑它是一个选项。现在我明白我的问题了警告:永远不要将用户输入直接放入originalText.Insert()的正则表达式(导致类似于SQL注入的问题);是的,这就是我要寻找的。谢谢你的回答!
var pattern = String.Format(@"\b(?!{0})\w+\b", Regex.Escape(userInput));