1

我想获取字符串中的每个数字并将其替换为双倍值。例如“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"
}
}

-编辑:感谢您的帮助。我想知道我的知识的正则表达式方法,我以后会得到一些不相关的东西。

4

2 回答 2

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*$_} )
}
于 2013-09-13T21:00:55.087 回答
2

根据此答案,您可以使用脚本块作为 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.

于 2013-09-14T03:44:43.947 回答