RegEx Magic

by May 25, 2011

The [RegEx] type has a method called Replace(), which can be used to replace text by using regular expressions. This line would replace the last octet of an IP address with a new fixed value:

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

 

In this example, the RegEx pattern represents a 1-3 digit number at the end of a text ("$"). It is replaced with a new value of "201."

If you want to replace the pattern with a calculated value, you can also submit a script block, which accepts the original value in $args[0]. The next line would actually increment the last octet of an IP address by 1:

PS > [Regex]::Replace('192.168.1.1', '\d{1,3}$', {[Int]$Args[0].Value + 1})
192.168.1.2

PS > [Regex]::Replace('192.168.1.13', '\d{1,3}$', {[Int]$Args[0].Value + 1})
192.168.1.14

 

 

Twitter This Tip!
ReTweet this Tip!