Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.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 - Fatal编程技术网

C# 正则表达式特殊字符

C# 正则表达式特殊字符,c#,regex,C#,Regex,代码用C#表示。 如果我在regex简单字符串中使用代码(例如fileName=“Test”),但是如果我使用特殊字符((()[]{}!),则会出现问题 fileName = "Test- ( ) [ ] {} ! . , ` ~ @ # % ; = - + &"; string pattern = ".*" + fileName + @"_\d{2}_\d{2}_\d{2}.xml"; //pattert = ".*" + "Test- ( ) [ ] {} ! . , ` ~ @

代码用C#表示。 如果我在regex简单字符串中使用代码(例如fileName=“Test”),但是如果我使用特殊字符((()[]{}!),则会出现问题

fileName = "Test- ( ) [ ] {} ! . , ` ~ @ # % ; = - + &"; 
string pattern = ".*" + fileName + @"_\d{2}_\d{2}_\d{2}.xml";
//pattert = ".*" + "Test- ( ) [ ] {} ! . , ` ~ @ # % ; = - + &" + @"_\d{2}_\d{2}_\d{2}.xml";
Regex rgx = new Regex(pattern);

if (rgx.IsMatch("..\\"+"Test- ( ) [ ] {} ! . , ` ~ @ # % ; = - + &_13_45_23.xml"))
{
...
}
有机会使用这些特殊字符。我如何解决这个问题

如果要安全地处理
文件名中的特殊字符,应使用该方法,例如:

string pattern = ".*" + Regex.Escape(fileName) + @"_\d{2}_\d{2}_\d{2}\.xml"; 
//                            and don't forget to escape the '.' here ^

使用
Regex.Escape

filename = Regex.Escape(filename)

您需要先转义
文件名
中的所有字符,然后再将其连接到
模式
。请参见if(..)中@L.B对该条件的解决方案。在if(..)中,要将rgx与“.\\”+“Test-()[]{}.”匹配,`~@\\%;=-+&&u13\u45\u23.xml“