Powershell正则表达式从一个替换匹配中获取值

时间:2013-09-13 20:45:37

标签: regex powershell replace multiple-matches

我想将每个数字放在一个字符串中,并用它的doubled值替换它。 例如“1 2 3 4 5”应成为“2 4 6 8 10”或“4 6 10”应为“8 12 20”

我想我差不多了,但是,我似乎无法从比赛中获得价值 我尝试使用'$ 1'或'\ 1',但都没有正常工作。

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:谢谢你的帮助。我想知道正则表达式方法对于我的知识包装我最后会得到一些无关的东西。

2 个答案:

答案 0 :(得分:2)

拆分字符串并将有效值转换为整数。

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

答案 1 :(得分:2)

您可以根据this answer使用脚本块作为MatchEvaluator委托。回答你的问题:

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

> 2 4 6 8 10 

$args[0]包含Match对象(而不是作者在另一个答案中所说的MatchEvaluator),因此$args[0].Value相当于matchObject.Groups[0].Value