20 Jun 2011

Using regex function to have a powerful split/replace functionality in Powershell

Powershell provides easy replace and split method to manipulate text/string values. They are easy to use but…if you want to replace content only on subsequent positions or split a string using a pattern containing more than a single character, you’ll fail.

Let’s take two examples.
Replace the last IP digit

$a = 'The IP Adress with the number 100 is:'

if you just had to replace the IP digit but not the text before, you have a problem.

The same for split.

$a = 'This is a combined string :which we want to split from here: and the show begins:'
$a.split('from here:')

The split method does only allow a single character as a split string.

To enhance this two methods take these two regex examples as a reference.

[Regex]::Replace('', '\d{1,3}$','201')

As you can see, the regex pattern function works also for split and replace methods within complex string content