Remove punctuation from string with Regex

前端 未结 2 937
栀梦
栀梦 2021-02-04 01:52

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;         


        
相关标签:
2条回答
  • 2021-02-04 02:34

    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

    0 讨论(0)
  • 2021-02-04 02:42

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

    0 讨论(0)
提交回复
热议问题