PowerTip: Replace Non-Alphabetic Characters in String


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

Hey, Scripting Guy! Question How can I use Windows PowerShell to replace a string that contains non-alphabetic characters
           (such as commas and periods)?

Hey, Scripting Guy! Answer Use the –Replace operator, and specify a regex pattern '[^a-zA-Z]', for example:

$a = 'Never a foot too far, even.'

$a -Replace '[^a-zA-Z]',''

Comments (1)

  1. Chris J Warwick says:

    Almost all the examples I see of the -replace operator fail to point out that when replacing with ” (nothing) the second parameter is not required.

    So,

    ‘xyz’ -replace ‘x’,”

    Can be written as:

    ‘xyz’ -replace ‘x’

    (Also, as regex in PowerShell is case insensitive by default, your pattern can be simplified to [^a-z])
    (…Case insensitivity doesn’t by default apply to .Net methods where [^a-zA-Z] would be required.)

Skip to main content