gpt4 book ai didi

regex - 如何查找和替换文本文件中所有出现的 "(percentage)%"并替换为用户提供的整数

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

我正在尝试使用正则表达式解析文本文件,将百分比作为字符串,并用百分比乘以用户提供的整数来替换结果。如果用户输入 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 等”

最佳答案

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

$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(', ')

关于regex - 如何查找和替换文本文件中所有出现的 "(percentage)%"并替换为用户提供的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57454706/

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