Remove special characters from a string except whitespace

17,751
[ ](?=[ ])|[^-_,A-Za-z0-9 ]+

Try this.See demo.Replace by empty string.See demo.

http://regex101.com/r/lZ5mN8/69

Share:
17,751
Coding Duchess
Author by

Coding Duchess

Software developer

Updated on June 26, 2022

Comments

  • Coding Duchess
    Coding Duchess almost 2 years

    I am looking for a regular expression to remove all special characters from a string, except whitespace. And maybe replace all multi- whitespaces with a single whitespace.

    For example "[one@ !two three-four]" should become "one two three-four"

    I tried using str = Regex.Replace(strTemp, "^[-_,A-Za-z0-9]$", "").Trim() but it does not work. I also tried few more but they either get rid of the whitespace or do not replace all the special characters.

  • Coding Duchess
    Coding Duchess over 9 years
    Thanks! It does not take care of extra spaces but works fine otherwise
  • vks
    vks over 9 years
    @ElenaDBA try now.took care of multiple spcaes.
  • Coding Duchess
    Coding Duchess over 9 years
    That's great! Thanks!