String Replace In PowerShell

String or text operations are one of the most popular operations in PowerShell. And the replacement operation is a popular operation for String data or variables. Replace will simply change the specified string pattern with a newly specified one. The string data type provides the -replace option or method which can be used to change the text.

String Replace Syntax

The replace options and method provide for string data types. The replace() method is provided by the string variables and -replace option is provided by string data or literals. First, take a look at the replace() method for the string variable.

  • STRING is the string variable we will replace specified OLD characters with the NEW characters.
  • OLD is the character that will be replaced with NEW characters.

The -replace option for the string data has the following syntax.


Replace Strings

We will start with a simple example. In the following example, the string is “” and the “tect” part will be changed with the “TECT” with the replace options and method.

$newstr = "" -replace "tect","TECT"

For a string variable you can use the following code where we will use the replace() method and provide the “tect” and “TECT” as parameters.

$newstr = "".replace("tect","TECT")

Multiple Replacement

The -replace option and replace() method can be used multiple times for replacement in a single line and statement. As the -replace option and replace() method returns a string type this option and method can be called in multiple times. In the following example, we will call the -replace option and replace() method multiple times .

$newstr = "" -replace "tect","TECT" -replace "windows","WINDOWS"

$newstr = "".replace("tect","TECT").replace("windows","WINDOWS")

Match Character or Word Groups with Regex

The -replace option and replace() method supports the regex (regular expression). Regex is used to match different patterns in a string. For example, \w+ will match a word. The -replace option and replace method uses the parenthesis () in order to store with a variable number. The complete string will be stored inside the$0 variable and the first parenthesis content will be stored in $1 and this will continue like this. In the following example, we will match the first word with the (\w+) regex and store it variable $1 . We will also use $0 variable for the complete string.

$newstr = 'hello world' -replace '(\w+) \w+','$1 $0'

//The $newstr will be
//hello hello windowstect

$newstr = 'hello world'.replace('(\w+) \w+','$1 $0')

//The $newstr will be
//hello hello windowstect
READ  How To Set Environment Variable For Windows?

Leave a Comment