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.
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.
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:
In PowerShell Core (v6.1+), you can use the -replace operator:
\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:
$_ contains a [System.Text.RegularExpressions.Match] instance with information about the match at hand; in the simplest case, $_.Value returns the matched text.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.
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