October 21st, 2014

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

Doctor Scripto
Scripter

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.

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.