PowerShell tricks – replace and transform a value within a string

tree

Most PowerShell users know already of the String.Replace method and the PowerShell -replace operator. While the latter is quite powerful with its support for regular expressions … :

#using string's replace method
'this is good'.Replace('good','quite good')
#using PowerShell's replace operator to remove duplicate words
'this this is a a test' -replace '\b(\w+)(\s+\1){1,}\b', '$1'

… there is an even more powerful option available for cases where the characters that we want to replace need to be “transformed” in some way. Let’s look two examples:

  1. Increase a number within a string by one e.g. ‘XX33.txt’ should turn into ‘XX34.txt’
  2. Capitalize the second word within a sentence string e.g. ‘this is a test’ should turn into ‘this IS a test’

For the two examples there are of course multiple ways to accomplish this using PowerShell without involving regex replace, but there might be situations where it is your only option. For those case the .net Regex.Replace method could become your new best friend. The method provides an overload that takes the following three arguments:

Parameter Description
Input string Text that contains the character(s) to be replaced
Pattern string The regex pattern that identifies the character(s) to be replaced
MatchEvaluator A scriptBlock that is being evaluated against the captured matched characters

The 3rd argument (MatchEvaluator) is the key to the solution as the scriptBlock automatically receives the captured characters as an argument it can be used to transform the match(es) using any method available. Let’s use the same to solve the two example problems:

The automatic $args[0] variable can be used to access the match(es) within the scriptBlock. Note that for the second example the ToUpper method is called on the Value property rather than the $args[0] variable directly. Furthermore the $counter variable needs to be declared in script scope (see also PowerShell scope write-up) in order to be visible within the scriptBlock for PowerShell version 3 or later.

shareThoughts


Photo Credit: Indy Kethdy via Compfight cc

Advertisements

I'd love to hear what you think

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 )

Google+ photo

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

Connecting to %s