PoshCode Logo PowerShell Code Repository

replace-regexgroup (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1295"></script>download | new post

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

  1. #region @3
  2. ## Function to do a regex replace of all matches with an expression per match that has local variables
  3. ##created automatically for the named groups so that you can use those varibles in your expression
  4. function replace-regexgroup ([regex]$regex, [string]$text ,[scriptblock] $replaceexpression)
  5. {
  6. $regex.Replace($text,{
  7.     $thematch = $args[0]
  8.     $groupnames = $regex.GetGroupNames()
  9.     for ($count = 0; $count -lt ( $thematch.groups.count) ; $count++)
  10.         {        
  11.          set-variable -name $($groupnames[$count]) -visibility private -value $($thematch.groups[$count] )
  12.         }    
  13.     if ($replaceexpression -ne $Null) { &$replaceexpression}
  14.     } )
  15. }
  16. $example = @"
  17. <P><a href="wiki://284_636">links to test page 2</a></P>
  18. <P><a href="wiki://109_49">
  19. "@
  20. replace-regexgroup 'wiki://(?<wholething>(?<folder>\d+)_(?<page>\d+))' $example { "$folder/$page/index.html" }
  21. #endregion

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me