Home > DeveloperSection > Forums > Regex Expression Special Charaters
jacob rasel
jacob rasel

Total Post:88

Points:616
Posted on    March-06-2014 11:09 PM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 782  View(s)
Rate this:

The code is in C#. If I use in regex simple string the code is working (for example fileName="Test"), but if I use special characters(- ( ) [ ] {} ! . , ` ~ @ # % ; = - + &) appear problems.

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"))

{

}

There are chances to use these special characters. How can I resolve this problem?



Pravesh Singh

Total Post:411

Points:2881
Posted on    March-06-2014 11:20 PM

Hi Jacob,

You should use the Regex.Escape method if you want to safely handle special characters in fileName, for example:

string pattern = ".*" + Regex.Escape(fileName) + @"_\d{2}_\d{2}_\d{2}\.xml";

// and don't forget to escape the '.' here ^


Don't want to miss updates? Please click the below button!

Follow MindStick