REGEX EXPRESSION SPECIAL CHARATERS

jacob rasel

Total Post:88

Points:616
Posted by  jacob rasel
 1059  View(s)
Ratings:
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?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Regex Expression Special Charaters

    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 ^

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!