Search code examples
regexpowershellreplacemultiple-matches

Powershell Regular Expressions getting values out of a -replace match


I want to take each number in a string and replace it with its doubled value. For instance "1 2 3 4 5 " should become "2 4 6 8 10" or "4 6 10 " should be "8 12 20"

I think I'm nearly there, however, I can't seem to get the value out of the match I've tried using '$1' or '\1' but neither worked correctly.

function doubleIt($digits = "1 2 3 4 5 ")
{
$digit_pattern = "\d\s+"
$matched = $digits -match $digit_pattern

if ($matched)
{
    $new_string = $digits -replace $digit_pattern, "$1 * 2 "
    $new_string
}
else
{
    "Incorrect input"
}
}

-Edit: Thanks for the help. I would like to know the Regular Expression method for my knowledge encase I end up with something unrelated later.


Solution

  • You can use a script block as the MatchEvaluator delegate as per this answer. To answer your question:

    [regex]::replace('1 2 3 4 5 ','\d+', { (0 + $args[0].Value) * 2 })
    
    > 2 4 6 8 10 
    

    $args[0] contains the Match object (not the MatchEvaluator as the author said in the other answer), so $args[0].Value is equivalent to matchObject.Groups[0].Value.