Remove punctuation from string with Regex

This code shows the full RegEx replace process and gives a sample Regex that only keeps letters, numbers, and spaces in a string - replacing ALL other characters with an empty string:

//Regex to remove all non-alphanumeric characters
System.Text.RegularExpressions.Regex TitleRegex = new 
System.Text.RegularExpressions.Regex("[^a-z0-9 ]+", 
System.Text.RegularExpressions.RegexOptions.IgnoreCase);

string ParsedString = TitleRegex.Replace(stringToParse, String.Empty);

return ParsedString;

And I've also stored the code here for future use: http://code.justingengo.com/post/Use%20a%20Regular%20Expression%20to%20Remove%20all%20Punctuation%20from%20a%20String

Sincerely,

S. Justin Gengo

http://www.justingengo.com


First, please read here for information on regular expressions. It's worth learning.

You can use this:

Regex.Replace("This is a test string, with lots of: punctuations; in it?!.", @"[^\w\s]", "");

Which means:

[   #Character block start.
^   #Not these characters (letters, numbers).
\w  #Word characters.
\s  #Space characters.
]   #Character block end.

In the end it reads "replace any character that is not a word character or a space character with nothing."

Tags:

C#

Regex