PowerShell: Removing Digits or Letters from a String (RegEx)

In this blog post I will cover removing digits and letters from a string. I will use an example string to show you how to manipulate that string. You can build on that example to achieve your goal.

Starting Point

We will start straightforward with the example string below.


Removing all Digits with the \d+ Statement (RegEx)

\d+ is a regex statement (Regular expressions). It will remove all digits from the string. Be aware, that you need to use the -replace statement to bring RegEx in action. The .NET method ().replace does not support regex.


$a -replace '\d+',''


That works out fine. Now let’s do the same with all letters.

Removing all Letters with the [a-zA-Z] Statement (RegEx)

The following code will remove all letters from the example string.


$a -replace '[a-zA-Z]',''


Removing specific Letters

As you may have already noticed my name is misspelled. My surname is Gruenauer, not Gruenbauer. Let’s correct this with this statement.


$a -replace 'b',''


PowerShell features multiple use of -replace. For example, I can remove all digits and the letter b at a time.


$a -replace 'b','' -replace '\d+',''

Removing all Digits and Characters with \w (RegEx)

The /w regex statement will remove a-z,A-Z and 0-9.


$a -replace '\w',''


Remove specific different Letters

For example, if you want to remove all a, b and c, then put the letters in square brackets.


$a -replace '[a-c]',''


Using replace multiple times

We can now combine the tasks above to achieve multiple actions in a one liner. The following one liner removes all digits, corrects my surename and replaces the domain outlook.com with the domain gmail.com in a single line.


$a -replace '\d+','' -replace 'b','' -replace 'outlook.com','gmail.com'


That’s it for today. I hope you have found what you are looking for in terms of removing digits and characters with PowerShell.

See also

PowerShell Data Types Cheat Sheet: String, Char, DateTime, Bool, Array, Hashtable, PSObject, Void, Math, TimeSpan

Understanding PowerShell Pipeline Parameter Binding

Categories: PowerShell

Tagged as:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.