I am trying to parse through a text file with regex finding percentages as strings and replacing the findings with the percentage multiplied by a user supplied integer. If the user inputs 400, then the code should return "120 x 8, 180 x 6, etc"
Tried doing a replace but it replaces all findings with the same string.
$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 } | % {"$_"}
User inputs: 400 Output: "120 x 8, 180 x 6, etc"
In PowerShell Core (v6.1+), you can take advantage of the fact that the -replace
operator'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
instance:
$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 }
The above yields (each percentage is replaced by the value that results from applying the percentage to $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
In Windows PowerShell, you have to make direct use of the .NET framework's [regex]
type:
$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 }
)
Note how parameter declaration param($m)
is used to declare the Match
instance that is passed to the script block ($_
is not defined int this case); alternatively, you could forgo the parameter declaration and use $args[0]
.