gpt4 book ai didi

regex - Powershell正则表达式从-replace匹配中获取值

转载 作者:行者123 更新时间:2023-12-03 00:52:39 25 4
gpt4 key购买 nike

我想获取字符串中的每个数字并将其替换为双倍值。
例如“1 2 3 4 5”应该变成“2 4 6 8 10”或者“4 6 10”应该变成“8 12 20”

我想我快到了,但是,我似乎无法从比赛中获得值(value)
我试过使用 '$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"
}
}

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

最佳答案

您可以根据 this answer 使用脚本 block 作为 MatchEvaluator 委托(delegate)。 .要回答您的问题:

[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 .

关于regex - Powershell正则表达式从-replace匹配中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18794954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com