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

标签 regex powershell replace multiple-matches

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

相关文章:

batch-file - 批处理文件用转义感叹号替换感叹号

python - 如何使用 Python Pandas 获取字符串中的第一个和最后一个(可变)字符

正则表达式匹配文本中出现两次的单词

javascript - 正则表达式和多个字符串

javascript - 正则表达式匹配模式以 ':' 结尾但不包含它

powershell - 在字符串中编写 powershell 函数

Powershell一旦锁定就不会发送 key

azure - 'az-getmetric 出现问题

xml - 如何在 Linux 中查找和替换多行文本?

python - 将十进制转换为罗马数字