First, I am completly new to regex and trying really hard to understand but getting very frustrated with it. Please bare with me here.
I am having problem understanding regex in PowerShell. I have tested a regex on both https://regexr.com/ and on https://regex101.com/r/zT5dL7/3. I then transfer the regex to powershell but the result is not what I am getting in powershell.
I need to get hold of the actual build number which looks like '(any number)-(any number)', where any number which over time will be bigger and bigger.
I get the string from a json from our jenkins api, convert it form json and get the string that holds the buildnumber.
$r = & $c @a | ConvertFrom-Json
$t= $r.fullDisplayName | Out-String
$t -replace '[^#0-9)][0-9-] [0-9]'
Ran regex [^#0-9)][0-9-] [0-9]
on input string #1737 - 1725-74033 - x64,x86
and I expect to get a reduced string like 1725-74033x64,x86
but instead I get #1737 - - ,
and I do not understand why.
Feel free to expand my regex if I can get rid of both x86
and x64
and the leading whitespace in the beginning. So the final result would be 1725-74033
.
CodePudding user response:
Apparently i didnt understand what -replace actually did as it removes the actual matches and is left with everything else. Above works just need to use -match instead of -replace and the result is in $Matches.
CodePudding user response:
What you're doing is replacing the characters which you are trying to capture.
I have assumed that the pattern you've put here is predictable. E.g. the length of the numbers and order of characters won't change.
The code
[string] $s = '#1737 - 1725-74033 - x64,x86'
$buildNumber = [regex]::Match($s, '#[0-9]{4}\s-\s([0-9]{4}-[0-9]{5})\s-\sx64,x86').Groups[1].Value
Write-Output $buildNumber
The output
PS C:\Users\ben> [string] $s = '#1737 - 1725-74033 - x64,x86'
$buildNumber = [regex]::Match($s, '#[0-9]{4}\s-\s([0-9]{4}-[0-9]{5})\s-\sx64,x86').Groups[1].Value
Write-Output $buildNumber
1725-74033
PS C:\Users\ben>
What this does is;
- match the pattern of your build output
- creates a group for the build number using
(capture in parens)
- gets the capture using regex Match() instead of regex replace.
Regex101 does a terrific job of explaining the individual bits of regex. https://regex101.com/r/xzak5z/1
CodePudding user response:
If you want to use -replace
to remove unwanted characters: (this follows your example data)
PS > $s = '#1737 - 1725-74033 - x64,x86'
PS > $s -replace '(^#\d - )|\s'
1725-74033-x64,x86
If you want to match desired characters: (this is 'AnyNumber-AnyNumber' per your descriptive text)
PS > $s -match '\d -\d '
True
PS > $matches
Name Value
---- -----
0 1725-74033