2014-03-03 218 views
-1

代码是用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")) 
{ 
... 
} 

有机会使用这些特殊字符。我该如何解决这个问题?

+1

你需要逃避里面'fileName'所有字符,在将它连接成'pattern'之前。请参阅@ L.B的解决方案。 – Diamondo25

+0

if(..)为真的条件。在if(..)中将rgx与“.. \\”+“Test-()[] {}!。,'〜@#%; = - +&_13_45_23.xml”相匹配 – Ice

回答

1

,如果你想在fileName安全地处理特殊字符,您应该使用Regex.Escape方法,例如:

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

使用Regex.Escape

filename = Regex.Escape(filename)