Banner Ad

Wednesday, January 6, 2016

Replace Special character from string using Regular expression in C#

By Francis   Posted at   6:04 PM   CodeSnippets No comments
In one of the forum post, the poster asked to
  1. Remove all the special character
  2. Then Remove the space and replace with _ (underscore) character
Say for example, if he gave, the input string as “Levi Jeans (Blue) & yellow 101 – 150Ah” and the output he wants as “Levi_Jeans_Blue_yellow_101_150ah”.
Solution:

            string yourInput = "Levi Jeans (Blue) & yellow 101 - 150Ah"; 
            Regex rgx = new Regex(@"[^a-zA-Z\d\s]"); 
            // Replace Special Charater and space with emptystring 
            string finalOutput = rgx.Replace(yourInput,""); 
            Console.WriteLine(finalOutput); 
            Regex rgx1 = new Regex("\\s+"); 
            // Replace space with underscore 
            finalOutput = rgx1.Replace(finalOutput, "_");

About Francis

Francis, an Associate at Cognizant. Having 7+ Years of experience in Microsoft web technologies.

0 comments :

Please give your valuable comments to improve the contents

Connect with Us