PowerTip: Use PowerShell to Replace Characters in String

The Scripting Guys


Summary: Use Windows PowerShell to replace non-alphabetic and non-number characters in a string.

Hey, Scripting Guy! Question How can I use Windows PowerShell to replace every non-alphabetic and non-number character in a string
           with a hyphen?

Hey, Scripting Guy! Answer Use the Windows PowerShell –Replace operator and the \w regular expression character class.
           The \w character class includes the letters a-z, A-Z, and numbers. Here is an example:

PS C:\> $s = 'abc.123,DEF&ghi'

PS C:\> $s -replace "\w", '-'


PS C:\>  

The Scripting Guys
Dr Scripto

Follow Dr   

No Comment.