December 6th, 2014

PowerTip: Use PowerShell to Replace Characters in String

Doctor Scripto
Scripter

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:\>  

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.

Feedback