PoshCode Archive  Artifact [b36ddf1770]

Artifact b36ddf17702e87651e63b98639ed21e5f5ea74749780ed190351d6023c715c1d:

  • File replace-regexgroup.ps1 — part of check-in [d96be5e896] at 2018-06-10 14:05:45 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: 5996
# x-archived: 2016-05-17T07:06:21
# x-published: 2016-08-31T10:41: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