Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

C# Regex to Replace All Special Characters with Space in String

Sep 26, 2013
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 RSS subscribe by email Subscribe by Email

3 comments :

Anonymous said...

good

muay thai kursu said...

Its very helpful. thx.

Krishnat Ranage said...

Very helpful code.....
But there is a small mistake in C# code. Third parameter (MatchEvaluator) should be " " instead of "-".
VB.Net code is correct.

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.