[英]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.