问题
I want to perform arithmetic operations on numbers in a string.
For example: SGJKR67
should become SGJKR68
.
Another one: NYSC34
should become NYSC35
.
Only numbers are changed, in this example both are increased by one.
回答1:
Using regex and Capturing Groups can solve your problem:
$reg = [regex]::new("([A-Z]+)(\d+)")
$m = $reg.Match("SGJKR67")
$digits = $m.Groups[2] # will be 67
$digits = $digit + 1; # or apply anything you want
$result = "$($m.Groups[1])$digits" # will be SGJKR and 68.
You will have 3 groups for your matches:
- The whole "word".
- The letters
- the digits.
回答2:
In PowerShell Core (v6.1+), you can use the -replace operator:
- with a regex (regular expression) for matching the embedded numbers
\d+
is a sequence of one or more (+
) digits (\d
)
and a script block ({ ... }) as the replacement operand, which allows you to dynamically determine replacement strings on a per-match basis:
- Inside the script block, which is called for every match, automatic variable $_ contains a [System.Text.RegularExpressions.Match] instance with information about the match at hand; in the simplest case,
$_.Value
returns the matched text.
- Inside the script block, which is called for every match, automatic variable $_ contains a [System.Text.RegularExpressions.Match] instance with information about the match at hand; in the simplest case,
PS> 'SGJKR67', 'NYSC34' -replace '\d+', { 1 + [int] $_.Value }
SGJKR68
NYSC35
In Windows PowerShell, where script-block replacement operands aren't supported, you must use the .NET [regex]
type's static .Replace() method directly:
PS> 'SGJKR67', 'NYSC34' | ForEach-Object {
[regex]::Replace($_, '\d+', { param($m) 1 + [int] $m.Value })
}
SGJKR68
NYSC35
Note: Unlike -replace
, [regex]::Match()
doesn't support passing an array of input strings, hence the use of a ForEach-Object call; inside its script block ({ ... }
), $_
refers to the input string at hand.
The approach is fundamentally the same, except that the match at hand (the [System.Text.RegularExpressions.Match]
instance) is passed as an argument to the script block, which parameter declaration param($m)
captures in variable $m
.
回答3:
You have to separate the numbers from the string, calculate the new number and return everything as string.
[System.String]$NumberInString = 'SGJKR68'
[System.String]$String = $NumberInString.Substring(0, 5)
[System.Int32]$Int = $NumberInString.Substring(5, 2)
$Int += 1
[System.String]$NewNumberInString = ($String + $Int)
$NewNumberInString
来源:https://stackoverflow.com/questions/58602659/how-to-increase-a-number-in-a-string-that-also-contains-letters