1

How would one go about writing a one size fits all powershell script that could extract specific numbers from a string? Let's say I have 3 computers and their names are GT0104MTR, GT0040MTR, and GT0444MTR. The numbers 104, 40, and 444 are the characters I want to extract..

How would I ignore any leading zeroes and grab from where the number begins and ends, even if the number ends with a zero?

I hope this makes sense and thanks for anything that points me in the right direction!

RThursty64
  • 25
  • 1
  • 5

3 Answers3

1

For the strings you give, this should work:

$strings = "GT0104MTR","GT0040MTR","GT0444MTR"

$strings | ForEach-Object {
    if($_ -match '0*(?<Number>([1-9][0-9]*))') {
        $matches.Number
    }
}

Which gives this output:

104
40
444

Note:

  • Identifiers with all-zero numbers in the input (e.g., GT0000MTR), if any, will be ignored.
mklement0
  • 382,024
  • 64
  • 607
  • 775
boxdog
  • 7,894
  • 2
  • 18
  • 27
1

here's a slightly different method that uses -replace to get rid of non-digits & then to get rid of leading zeros. [grin]

$InStuff = @'
GT0104MTR
GT0040MTR
GT0444MTR
GT0555MTR
GT0666MTR
GT1001MTR
'@ -split [System.Environment]::NewLine

$InStuff -replace '[^0-9]' -replace '^0{1,}'

output ...

104
40
444
555
666
1001
Lee_Dailey
  • 7,292
  • 2
  • 22
  • 26
1

To offer a concise alternative with the -replace operator:

PS> 'GT0104MTR', 'GT0040MTR', 'GT0444MTR' -replace '.*\D0*(\d+).*', '$1'
104
40
444

Note:

  • If there are identifiers with all-zero numbers (e.g., GT0000MTR), 0 is extracted from them.

  • This contrasts with boxdog's solution, which ignores such identifiers.

Since the identifiers are computer names, encountering all-zero numbers strikes me as unlikely, however.

mklement0
  • 382,024
  • 64
  • 607
  • 775