[英]Regex Expression Special Characters
该代码在C#中。 如果我在正则表达式中使用简单字符串,则代码可以正常工作(例如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"))
{
...
}
有机会使用这些特殊字符。 我该如何解决这个问题?
使用Regex.Escape
filename = Regex.Escape(filename)
如果要安全地处理fileName
特殊字符,则应使用Regex.Escape
方法,例如:
string pattern = ".*" + Regex.Escape(fileName) + @"_\d{2}_\d{2}_\d{2}\.xml";
// and don't forget to escape the '.' here ^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.