PowerShell: How to Replace Text with Wildcard


You can use the following methods to replace text in a string using wildcards in PowerShell:

Method 1: Replace all text before specific character

$original_string -replace '^[^web]*', ''

This particular example will replace all text before ‘web’ in the string variable named original_string.

Method 2: Replace all text after specific character

$original_string -replace '(.+?)web.+', '$1'

This particular example will replace all text after and including ‘web’ in the string variable named original_string.

The following examples show how to use each method in practice.

Example 1: Use Wildcard to Replace All Text Before Specific Character in PowerShell

Suppose that we would like to use PowerShell to remove all text before the substring ‘web’ in a particular string.

We can use the following syntax to do so:

$original_string = "mycoolwebsite.com"
$original_string -replace '^[^web]*', ''

The following screenshot shows how to use this syntax in practice:

PowerShell replace text before string using wildcard

Notice that all characters before ‘web’ in the string have been replaced with nothing.

The original string was: mycoolwebsite.com

The new string is: website.com

Example 2: Use Wildcard to Replace All Text After Specific Character in PowerShell

Suppose that we would like to use PowerShell to remove all text after and including the substring ‘web’ in a particular string.

We can use the following syntax to do so:

$original_string = "mycoolwebsite.com"
$original_string -replace '(.+?)web.+', '$1'

The following screenshot shows how to use this syntax in practice:

PowerShell use wildcard to replace all text after string

Notice that all characters after and including ‘web’ in the string have been replaced with nothing.

The original string was: mycoolwebsite.com

The new string is: mycool

Note: In both examples in this tutorial we used wildcards to replace all characters before or after a specific pattern, but you could use similar syntax to replace characters with a different set of characters if you’d like.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Text in String
PowerShell: How to Concatenate Strings

Leave a Reply