I think Powershell’s -match operator deserves its own blog post because it does so much. I’ve been automating our build process using Powershell and I gained a lot of respect for this operator. The examples below, would usually refer to the SVN url parsing.
Firstly, it returns true ($true in Powershell) if the original string matches the regex expression you passed into it. For example,
$string = &quot;Hello&quot; $string -match &quot;Hello&quot; #return true $string -cmatch &quot;hello&quot; #return false, cmatch performs case-sensitive match $string -cmatch &quot;[H|h]ello&quot; #return true
In addition to regular matching the -match operator will populate a special $matches variable. For example
$string = &quot;Hello World&quot; $string -match &quot;Hello&quot; $matches #prints &quot;Hello&quot; $string = &quot;Hello World&quot; $string -match &quot;(?'first'Hello)&quot; Name Value ---- ----- first Hello 0 Hello
Group Matching and Replacing
If you are crafty enough, you can come up with a match and replace strategy for the strings you are working with. For example, if you have to figure out the full path of the svn path if you know the name of the tag, given the current branch path, you’ll do the following:
$url = &quot;http://subversion.url.com/project/branches/VERSION-1.0/path/to/code&quot; $search = &quot;(.*)(?'branch'branches/[^/]*)(.*)&quot; #Generates 3 groups (1,2, and branch) $url -match $search True $matches Name Value ---- ----- branch branches/VERSION-1.0 2 /path/to/code 1 http://subversion.url.com/project/ 0 http://subversion.url.com/project/branches/VERSION-1.0/path/to/code #use the replace method of the Match object to replace branche path with tag path: $newUrl = $matches.Replace($matches['branch'], 'tags/TAG-123') #replaces branch path with new tag path $newUrl http://subversion.url.com/project/tags/TAG-123/path/to/code