gpt4 book ai didi

c# - 转义正则表达式中的特殊字符

转载 作者:IT王子 更新时间:2023-10-29 04:47:10 25 4
gpt4 key购买 nike

有没有办法从字符串中转义正则表达式中的特殊字符,例如 []()* 等?

基本上,我要求用户输入一个字符串,并且我希望能够使用正则表达式在数据库中进行搜索。我遇到的一些问题是太多)的[x-y] range in reverse order等。

所以我想做的是编写一个函数来替换用户输入。例如,将(替换为\(,将[替换为\[

是否有用于正则表达式的内置函数来执行此操作?如果我必须从头开始编写一个函数,有没有一种方法可以轻松地计算所有字符,而不是一个一个地编写替换语句?

我正在使用 Visual Studio 2010 在 C# 中编写我的程序

最佳答案

您可以使用 .NET 的内置 Regex.Escape为了这。复制自微软的示例:

string pattern = Regex.Escape("[") + "(.*?)]"; 
string input = "The animal [what kind?] was visible [by whom?] from the window.";

MatchCollection matches = Regex.Matches(input, pattern);
int commentNumber = 0;
Console.WriteLine("{0} produces the following matches:", pattern);
foreach (Match match in matches)
Console.WriteLine(" {0}: {1}", ++commentNumber, match.Value);

// This example displays the following output:
// \[(.*?)] produces the following matches:
// 1: [what kind?]
// 2: [by whom?]

关于c# - 转义正则表达式中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20505914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com