manoj kumar
manoj kumar

Reputation: 49

How to increase a number in a string that also contains letters?

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.

Upvotes: 2

Views: 198

Answers (3)

mklement0
mklement0

Reputation: 437953

In PowerShell Core (v6.1+), you can use the -replace operator:

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.

Upvotes: 1

Didier Aupest
Didier Aupest

Reputation: 3367

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.

Upvotes: 1

Patrick
Patrick

Reputation: 2208

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

Upvotes: 0

Related Questions