我正在尝试解析一个文本文件,将正则表达式查找百分比作为字符串,并将结果替换为百分比乘以用户提供的整数。如果用户输入 400,则代码应返回"120 x 8、180 x 6 等">
尝试执行替换,但它用相同的字符串替换所有发现。
$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 等">
在 PowerShellCore(v6.1+( 中,您可以利用以下事实:-replace
运算符的替换操作数现在可以执行动态替换,通过脚本块,手头的匹配项作为$_
传递到该脚本块中,作为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
在WindowsPowerShell中,您必须直接使用.NET framework的[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(', ')