Search code examples
c#regexlanguage-agnosticpunctuation

Remove punctuation from string with Regex


I'm really bad with Regex but I want to remove all these .,;:'"$#@!?/\*&^-+ out of a string.

string x = "This is a test string, with lots of: punctuations; in it?!.";

How can I do that?


Solution

  • 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."