Replace special characters in c# using regex

Hello Readers,

This post emphasizes on how to easily replace special characters from a given string using REGEX in both the programming languages – C# and VB.NET.

Replace special characters in c# using regex

While working on one of the modules, I came across a requirement to replace all special characters with spaces (” “) and some of them with nothing (“”). Hence, thought of sharing the code to replace special characters with spaces as it might be helpful for some of you fellow developers.

Replace special characters in c# using regex Click To Tweet

In order to replace all special characters in a string with spaces we need to write code like as shown below:

C# Code

using System;
using System.Text.RegularExpressions;

namespace RegexExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string randomString = "welcome@to-dipendra#shekhawat.com";

            string newString = Regex.Replace(randomString, "[^a-zA-Z0-9_]+", " ");

            Console.WriteLine(newString);

            Console.ReadLine();
        }
    }
}

VB.NET Code

Imports System
Imports System.Text.RegularExpressions

Namespace ConsoleApplication3
    Class Program
        Private Shared Sub Main(args As String())

            Dim str As String = "welcome@to-dipendra#shekhawat.com"

            Dim replacestr As String = Regex.Replace(str, "[^a-zA-Z0-9_]+", " ")

            Console.WriteLine(replacestr)

            Console.ReadLine()

        End Sub

    End Class

End Namespace

Output

Executing the above-mentioned piece of code will generate us the output as shown below:

| welcome to dipendra shekhawat com

Also, you can use LINQ for achieving the same.


Public Shared Function CleanFileName(fileName As String) As String
   Return Path.GetInvalidFileNameChars().Aggregate(fileName, Function(current, c) current.Replace(c.ToString(), String.Empty))
End Function

Concluding with a hope that this post helped you to solve your problem.

What do you think?

Dear Reader,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. I would love to hear from my readers. Please share along with your friends and help them to learn.

Happy Coding!