如何在文本文件中查找和替换所有出现的“(百分比)%”并替换为用户提供的整数

How to find and replace all occurrences of "(percentage)%" in a text file and replace with a user supplied Integer

我正在尝试使用正则表达式解析一个文本文件,找到字符串形式的百分比,并将结果替换为乘以用户提供的整数的百分比。如果用户输入 400,那么代码应该 return "120 x 8, 180 x 6, etc"

尝试进行替换,但它用相同的字符串替换了所有结果。

$body = "30% x 8, 45% x 6, 55% x 4, 60% x 2, 65% x 1, 70% x 1, 75% x 1, 80% x 1, 72.5 % x 4、70% x 4、67.5% x 4、65% x 4"

$regex1 = "(\d+(\.\d+)?%)"
$regex2 = "(\d+(\.\d+)?)"
$regex3 = "\bx \d{0,2}\b"
$regex4 = "\b% x \d{0,2}\b"
$percent = $body | select-string  -Pattern $regex1 -AllMatches | % { $_.Matches } | % { [string]$_.Value } | % {"$_,"}
$reps = $body | select-string  -Pattern $regex4 -AllMatches | % { $_.Matches } | % { $_.Value } | % {"$_,"}
$weights = $body | select-string  -Pattern $regex1 -AllMatches | % { $_.Matches } | % { $_.Value } | select-string -Pattern $regex2 -AllMatches | % { $_.Matches } | % { ([int]$_.Value / 100) }
$reps_percent = $body | select-string  -Pattern $regex4 -AllMatches | % { $_.Matches } | % { [string]$_.Value } |select-string -Pattern $regex3 -AllMatches | % { $_.Matches } | % { [string]$_.Value } | % {"$_"} 

用户输入:400 输出: “120 x 8、180 x 6 等”

在 PowerShell Core (v6.1+) 中,您可以利用 's replacement operand can now perform dynamic replacements, via a script block to which the match at hand is passed as $_, as a System.Text.RegularExpressions.Match 实例:

$body = '30% x 8,    45% x 6,    55% x 4,   60% x 2,   65% x 1,   70% x 1,   75% x 1,   80% x 1, 72.5% x 4,   70% x 4,   67.5% x 4,   65% x 4'

# Sample user input (the value for which to calculate percentages).
$value = 400 

$body -replace 
  '\b(\d+(?:\.\d+)?)% x (\d+)',
  { '{0} x {1}' -f ([double] $_.Groups[1].Value * $value / 100), $_.Groups[2].Value }

上面的产量(每个百分比都替换为将百分比应用于 $value 后的值):

120 x 8,    180 x 6,    220 x 4,   240 x 2,   260 x 1,   280 x 1,   300 x 1,   320 x 1, 290 x 4,   280 x 4,   270 x 4,   260 x 4

Windows PowerShell中,你必须直接使用.NET框架的[regex]类型:

$body = '30% x 8,    45% x 6,    55% x 4,   60% x 2,   65% x 1,   70% x 1,   75% x 1,   80% x 1, 72.5% x 4,   70% x 4,   67.5% x 4,   65% x 4'

$scalePercentage = 400 

[regex]::Replace(
  $body,
  '\b(\d+(?:\.\d+)?)% x (\d+)',
  { param($m) '{0} x {1}' -f ([double] $m.Groups[1].Value * $scalePercentage / 100), $m.Groups[2].Value }
)

请注意参数声明 param($m) 如何用于声明传递给脚本块的 Match 实例($_ 而不是 在这种情况下定义);或者,您可以放弃参数声明并使用 $args[0].

无需正则表达式即可轻松完成:

$body  = "30% x 8, 45% x 6, 55% x 4, 60% x 2, 65% x 1, 70% x 1, 75% x 1, 80% x 1, 72.5% x 4, 70% x 4, 67.5% x 4, 65% x 4"

$userInput        = 400

$calculationArray = $body -split ','
$body             = ''

foreach( $pattern in $calculationArray ) {
    $percent = @($pattern -split '%')[0] -as [int]
    $result  = $userInput * ($percent / 100)
    $body   += $result.ToString() + @($pattern -split '%')[1] + ', '
}

$body.Trim(', ')