Trevor Tiernan
Trevor Tiernan

Reputation: 522

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.

Upvotes: 1

Views: 1012

Answers (2)

Alan Moore
Alan Moore

Reputation: 75232

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.

Upvotes: 2

Shay Levy
Shay Levy

Reputation: 126762

Split the string and cast valid values to integers.

function doubleIt($digits = "1 2 3 4 5")
{
    #[string](-split $digits -as [int[]] | ForEach-Object {$_*2})
    [string](-split $digits | where {$_ -as [int]} | foreach {2*$_} )
}

Upvotes: 2

Related Questions