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

Doctor Scripto

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.

0 comments

Discussion is closed.

Feedback usabilla icon