Introduction: 
Here I will explain how to use regular
expression or regex in c#
to replace all special characters with space in string using c#,
vb.net.
Description: 
In previous articles I explained constructors in c#, polymorphism example in c#, delegates in c# with example, Difference b/w compile time and runtime polymorphism, sealed classes in c#.net and many articles relating to c#,
vb.net,
code snippets. Now I will explain how to replace all
special characters in string with space in c#,
vb.net.
C#
Code to replace special characters with spaces
If we want to replace all special characters in string
with spaces we need to write code like as shown below
using System; 
using System.Text.RegularExpressions; 
namespace ConsoleApplication3 
{ 
class Program 
{ 
static void Main(string[] args) 
{ 
string str = "welcome@to-aspdotnet#sueresh.com"; 
string replacestr= Regex.Replace(str,
  "[^a-zA-Z0-9_]+", " "); 
Console.WriteLine(replacestr); 
Console.ReadLine(); 
} 
} 
} 
 | 
 
VB.NET Code
Imports System.Text.RegularExpressions 
Module Module1 
Sub Main() 
Dim str As String = "welcome@to-aspdotnet#sueresh.com" 
Dim replacestr As String = Regex.Replace(str, "[^a-zA-Z0-9_]+", "
  ") 
Console.WriteLine(replacestr) 
Console.ReadLine() 
End Sub 
End Module 
 | 
 
If we run above code we will get output like as shown
below
Output
welcome to
  aspdotnet suresh com 
 | 
 
I hope it helps you to solve your problem. Happy coding…
| 
 If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.  | 
|||
 
                                        Subscribe by RSS
                                      
 
                                        Subscribe by Email
                                      
 | 
|||
                                        Subscribe by RSS
                                      
                                        Subscribe by Email
                                      
6 comments :
good
Its very helpful. thx.
Very helpful code.....
But there is a small mistake in C# code. Third parameter (MatchEvaluator) should be " " instead of "-".
VB.Net code is correct.
I really like the post..
Sir i have to insert special character in ms access database like 44'12 using c# plz help
It is very Helpfull code sir.
But i want whenever we insert at a time multiple special characters on that time it is taken single space but,i want how many special characters is there that much of spaces we want.
Note: Only a member of this blog may post a comment.