PowerTip: Replace Characters in String that Is Not Part of Group


Summary: Use Windows PowerShell to replace all characters in a string that is not part of a group.

Hey, Scripting Guy! Question How can I use Windows PowerShell to remove all the non-alphabetic characters in the following string?
           (The single quotation marks are not part of the string.)

'({Abcde})'

Hey, Scripting Guy! Answer Create a regular expression pattern (character group) that includes the alphabetic characters a – z and A – Z,
           and use the "not in character group" operator (^) at the beginning of the pattern. Use the Windows PowerShell 
           -replace operator, and write the value back to the variable. Here is an example:

PS C:> $a = '({Abcde})'

PS C:> $a -replace '[^a-zA-Z]',''

Abcde

Note  This code uses single quotation marks. The replacement string uses two back-to-back single
quotation marks.

Comments (4)

  1. David Wyatt says:

    You can shorten this slightly to just: $a -replace ‘[^a-z]’

    The -replace operator is not case sensitive by default, and if you don’t specify a second right operand, it defaults to replacing the matches with nothing.

  2. James Brown says:

    Works with numbers, too: $a -replace ‘[^a-z0-9]’

Skip to main content