逃避正则表达式特殊字符 [英] Escape Special Character in Regex
问题描述
有没有办法逃避的正则表达式[]的特殊字符,如()*
及其他,从一个字符串?
Is there a way to escape the special characters in regex, such as []()*
and others, from a string?
基本上,我要求用户输入一个字符串,我希望能够在使用正则表达式的数据库进行搜索。有些我跑进是太多)的
或 [XY]范围内以相反的顺序
等问题
Basically, I'm asking the user to input a string, and I want to be able to search in the database using regex. Some of the issues I ran into are too many)'s
or [x-y] range in reverse order
, etc.
所以,我想要做的就是写一个函数做用户输入取代。例如,将(
与 \(
,将 [
与 \ [
So what I want to do is write a function to do replace on the user input. For example, replacing (
with \(
, replacing [
with \[
有一个内置的功能正则表达式这样做呢?如果我有从头开始编写一个函数,有没有办法可以轻松地解释,而不是写一个替换说明一中的所有字符?
Is there a built-in function for regex to do so? And if I have to write a function from scratch, is there a way to account all characters easily instead of writing the replace statement one by one?
我在C#中使用写我的程序Visual Studio 2010中
I'm writing my program in C# using Visual Studio 2010
推荐答案
您可以使用.NET的内置的 Regex.Escape 这个来自微软的例子复制:
You can use .NET's built in Regex.Escape for this. Copied from Microsoft's example:
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?]
这篇关于逃避正则表达式特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!