Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The original string can be found here.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading