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.
In order to replace all special characters in a string with spaces we need to write code like as shown below:
static void Main(string args)
string randomString = "welcome@to-dipendra#shekhawat.com";
string newString = Regex.Replace(randomString, "[^a-zA-Z0-9_]+", " ");
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_]+", "&nbsp;")
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))
Concluding with a hope that this post helped you to solve your problem.
What do you think?
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.