Friday, June 19, 2009

Remove all special characters from string

What is easiest way to remove all special characters from string using Powershell?

Of course regex, but here you can see how it works:
[System.Text.RegularExpressions.Regex]::Replace($Text,"[^1-9a-zA-Z_]"," ");

 

For example

PS C:\Users\Martin> [System.Text.RegularExpressions.Regex]::Replace("I got cool
n1ck%/\/\name($7&","[^1-9a-zA-Z_]"," ");
I got cool n1ck     name

 

I am replacing special characters with space, however of course you can use whatever you want – typically “_”

3 comments:

Jason Graham said...

Thanks for taking the time to share this. You saved me at least a couple of hours with this short blog post.

Anonymous said...

How to remove [] characters ?

Unknown said...

Weakness of attitude becomes weakness of charater. See the link below for more info.


#character
www.ufgop.org