Replace operator

The -replace operator will work very similarly to the -match operator, and allows for the systematic replacement of strings using regular expressions:

# Simple usage of -replace
'PowerShell is hard.' -replace 'hard', 'easy' # 'PowerShell is easy.'

This statement searches for the hard statement and replaces it with easy. In addition, you can use dedicated regular expressions and replace many values, as shown in the following example:

# Using Regex to switch words
"PowerShell Awesomeness" -replace '(.*) (.*)','$2 $1' # 'Awesomeness PowerShell'

 To understand this line of code, let's use our previously learned -match statement:

# Explaining the example with -match
"PowerShell Awesomeness" -match '(.*) (.*)'
$Matches

# Output of $Matches:
# Name Value
# ---- -----
# 2 Awesomeness
# 1 PowerShell
# 0 PowerShell Awesomeness

The -match statement returns true, and shows us that matches for this regular expression have been found. Now, the $matches variable returns us the following three values. You can show them by using the indexing operator, as follows:

$Matches[0] # PowerShell Awesomeness
$Matches[1] # PowerShell
$Matches[2] # Awesomeness

You can see that in the [1] index, the PowerShell string is included, and in the index [2], the Awesomeness string is included. If you take a look at the previous statement with the -replace operator, you will recognize that we actually used these indices to make the replacement. This can become a very powerful tool in more complex scenarios, but for now, we will not go into this topic any further.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.32.86