PoshCode Archive  Artifact Content

Artifact be3ce010f966b07e96c04e72acd99dd2089ad643eb7e7b69e8ee1e66557faacd:

  • File replace-regexgroup.ps1 — part of check-in [9fe08bf532] at 2018-06-10 12:56:49 on branch trunk — Function to do a regex replace of all matches with an expression per match that has local variables (user: karl prosser size: 1412)

# encoding: ascii
# api: powershell
# title: replace-regexgroup
# description: Function to do a regex replace of all matches with an expression per match that has local variables
# version: 0.1
# type: function
# author: karl prosser
# license: CC0
# function: replace-regexgroup
# x-poshcode-id: 1295
# x-archived: 2015-09-25T05:15:56
# x-published: 2009-08-26T09:20:00
#
# created automatically for the named groups so that you can use those varibles in your expression
#
#region @3
## Function to do a regex replace of all matches with an expression per match that has local variables
##created automatically for the named groups so that you can use those varibles in your expression
function replace-regexgroup ([regex]$regex, [string]$text ,[scriptblock] $replaceexpression)
{
$regex.Replace($text,{
    $thematch = $args[0]
    $groupnames = $regex.GetGroupNames()
    for ($count = 0; $count -lt ( $thematch.groups.count) ; $count++)
        {        
         set-variable -name $($groupnames[$count]) -visibility private -value $($thematch.groups[$count] ) 
        }    
    if ($replaceexpression -ne $Null) { &$replaceexpression}
    } )
}
$example = @"
<P><a href="wiki://284_636">links to test page 2</a></P>
<P><a href="wiki://109_49">
"@
replace-regexgroup 'wiki://(?<wholething>(?<folder>\d+)_(?<page>\d+))' $example { "$folder/$page/index.html" }
#endregion