PowerTip: Use PowerShell to Replace Characters in String

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

Comments (4)

  1. Anonymous says:

    Jason used "W" – this doen’t work. Using "w" like in the example above works fine!

  2. Jason says:

    I may be a bit slow today but isn’t this the opposite of what is being asked for?

    By using the w you are replacing every alphabetic and number character not every non-alphabetic and non-number character.

    You can reverse the outcome and get replace all the non-alphabetic characters by using a uppercase W instead.

    PS C:> $s = ‘abc.123,DEF&ghi’
    PS C:> $s -replace "W", ‘-‘
    PS C:>

  3. Mike Kuhn says:

    The script replaces all alphabetic and numeric characters with hyphens instead of replacing all non-alphabetic and non-numeric with hyphens. As Jason points out a NOT is missing from the expression

  4. paul says:

    Thanks for the example. One potential typo. I think you meant to say "replace every alphabetic and number character" instead of non.

Skip to main content