Why this Powershell Regex for serial numbers returns everything with Select-String?

48 views Asked by At

I'm trying to get the first serial number of Chromedriver from this string in Powershell with Select-String, but the regex returns everything: '\d{1,4}.\d{1,4}.\d{1,4}.\d{1,4}'.

The regex works well in regex101 and regexr and I've been checking other Powershell regex examples, even this guide. But the shell returns the whole string

'{"timestamp":"2023-08-04T13:08:44.174Z","channels":{"Stable":{"channel":"Stable","version":"115.0.5790.170","revision":"1148114"},"Beta":{"channel":"Beta","version":"116.0.5845.62","revision":"1160321"},"Dev":{"channel":"Dev","version":"117.0.5911.2","revision":"1175078"},"Canary":{"channel":"Canary","version":"117.0.5929.0","revision":"1179256"}}}' | Select-String -Pattern '\d{1,4}\.\d{1,4}\.\d{1,4}\.\d{1,4}

Why doesn't return the first serial number "115.0.5790.170"?

The original string can be found here.

1

There are 1 answers

0
Santiago Squarzon On BEST ANSWER

The regex is working properly just that you're missing the expansion of the matched value:

'{"timestamp":"2023-08-04T13:08:44.174Z","channels":{"Stable":{"channel":"Stable","version":"115.0.5790.170","revision":"1148114"},"Beta":{"channel":"Beta","version":"116.0.5845.62","revision":"1160321"},"Dev":{"channel":"Dev","version":"117.0.5911.2","revision":"1175078"},"Canary":{"channel":"Canary","version":"117.0.5929.0","revision":"1179256"}}}' |
    Select-String -Pattern '\d{1,4}\.\d{1,4}\.\d{1,4}\.\d{1,4}' |
    ForEach-Object { $_.Matches.Value } # Outputs: 115.0.5790.170

Taking a step back, there is no reason to use regex for this when what you have is a valid Json string, use ConvertFrom-Json and then you can use dot notation:

$json = $string | ConvertFrom-Json
$json.channels.Stable.version # Outputs: 115.0.5790.170