Using PowerShell Regex Replace

There are two methods to use for text replacement in PowerShell – replace() method or -replace operator.

In this article, we will cover the syntaxes of the two methods and work through some examples of how to use them. We will mainly focus on using regex in this guide, but you can easily tweak the code to work with literal strings if that fits your needs.

Method 1: Using replace() Method with Regex Wrapper

In most cases, the replace() method uses simple string matching and replacement with no regex matching. But we can repurpose it using the [regex] wrapper, as shown in the syntax below.

Where <regex> is the regular expression you want to use for replacement, <input> is the string we want to do the replacement on, and <substitute> is the string or characters to use for replacement.

You can also reduce that syntax into a one-liner, as shown below.

Method 2: Using the -replace Operator

The -replace operator has the following syntax.

Notice that, in this method, we do not need a regex wrapper. By default, the -replace operator will understand the “<pattern>” as a regular expression.

Note: The -replace operator is case-insensitive by default. To make it case-sensitive, use -creplace, and to make it explicitly case-insensitive, use -ireplace.

Let’s now see some examples of how to use the -replace operator.

Examples

This Section covers some examples of how to use the -replace operator or replace() method with regular expressions. The first example shows how to use both techniques then we will stick to one. You are free to pick your poison, though.

We will start with the code in each example and then explain the pattern afterward.

Example 1: Replacing the last character in the string

Output:

If you need my help, please let me kno@

The pattern: “.$”

Explanation: The “.” wildcard character matches any single character except the newline character (“\n”); $ matches the end of a string. That means the pattern “.$” matches the last character in a string.

Using the Replace() method, we can rewrite the code above as follows.

Output:

If you need my help, please let me kno@

Example 2: Replace a word in a string

Output:

If you need my xyz, please let me know and I will xyz

The pattern: “bhelp\b”

Explanation: \b is an anchor that matches the boundary between alphanumeric and nonalphanumeric characters. In a nutshell, it matches the word boundaries in a string.

That means when we use the pattern “bhelp\b”, we want to match the word “help”. This will match the word help in “I can help you” but not “I canhelp you”. In the latter, the substring “help” is not a word in itself but rather part of a word.

Example 3: Replace the first or the last word of a string

The following code snippet replaces the first word of the $string with “xyz”.

Output:

xyz you need my help, please let me know

The anchor “^” matches the beginning of the word, \w matches an alphanumeric character, and + matches one or more elements of the previous character. Therefore, “^\w+\b” matches one or more alphanumeric characters (\w+) followed by a word boundary (\b) at the beginning (^) of the string

We can tweak the previous code slightly if we want to replace the last word. All we need to do is to use the $ anchor to match the end of the string (as discussed in Example 1).

Output:

If you need my help, please let me xyz

Note: If you have a punctuation mark at the end of the string, the code snippet above won’t work. In that case, use the following

Output:

If you need my help, please let me xyz

The “\W*” expression matches zero or more non-word characters.

Example 4: Replace multiple words

The following PowerShell code replaces “help” or “know” with “xyz”.

Output:

If you need my xyz, please let me xyz and I will xyz. I will always xyz.

You can replace all words starting with m or h with the code below.

Output:

If you need xyz xyz, please let xyz know and I will xyz. I will always xyz.

Lastly, if you have a long list of replacements, consider parsing the values as arrays and use the -Join operator to join them with the “|” operator. Here is how -Join works.

Output:

you|me|I|will

Note that the output gives us a regex that can replace four values in a string.

Output:

xyzf xyz need xyz help, please let xyz xyz and xyz xyz help. xyz xyz always help.

Example 5: Replacing punctuation marks

This following code example finds and replaces punctuation marks with an empty string (effectively removing them).

Output:

If you need my help please let me know

The pattern: “[\p{P}<>^|]”

Explanation: [ ] is a set anchor – it holds a set of characters to be matched; for example, [ae] matches “a” in “park” and “a” and “e” in “east”. In our case, we want to march \p{P} (Unicode punctuation marks), <, >, ^, and |.

Note from the pattern that \p{P} may not match all punctuation marks in your string. If that is the case, here is an alternative code

Output:

If you need my help please let me know

The pattern: “[^\w\d\s]+”

Explanation: When ^ is used as the first character in the set [ ], it means negation. Therefore, “[^\w\d\s]+” will match any character that is not a word-character (\w), digit (\d) or whitespace (\s). Therefore, in most cases, the pattern will match punctuations.

Example 6: Replacing numbers

The digits 0 through 9 are captured by the set [0-9] or \d. The following code will replace all unsigned numbers with an empty string.

Output:

If you need my help, please let me know.

The code above will fail for signed numbers, e.g. -67 and +93. Let’s fix that.

Output:

If you ne_ed my help, plea_se le_t me kn_ow.

Once again, the code above will not capture all the numbers. In particular, it will not capture decimal numbers, e.g. 3.142, -2.78. We can update the code above as follows to fix that inefficiency.

Output:

If you ne_ed my help, plea_se le_t me kn_ow.

The last code snippet can now capture all numbers – integers and floats – signed or not signed.

Example 7: Replace the first x or the last x characters

Based on our discussions in the previous examples, the following examples should be easy to grasp.

Output:

_u need my help, please let me know

Output:

If you need my help, please let m_

Example 8: Replacing white spaces

The whitespace(s) are captured by “\s+”. The following example replaces whitespaces with an underscore (_).

Output:

If_you_need_my_help,_please_let_me_know

Example 9: Capturing and replacing groups

Groups in PowerShell regex are captured using parenthesis in the expression, and you can use numbers or names to identify the groups.

Suppose I have a phone number “+254 712 123 456”, whose digits can be grouped into four segments “254” as country code (group 1), 712 as area code (group 2), 123 as identifier 1 (group 3), and 456 as identifier 2 (group 4). We intend to replace “+254” with 0.

Here is how to do that with numbered groups.

Output:

0 712123456

And here is how to make the replacement with named groups.

Output:

0 712123456

Note that for named groups, you use the syntax “(?<name>…)” to define a captured group in the expression.

Conclusion

This guide discussed how to make regex replacements in PowerShell. If, after going through the examples given, you do not find what fits your used cases, the following reference materials could help: