为什么这个用于序列号的Powershell Regex使用Select-String返回所有内容?

sqxo8psd  于 2023-08-08  发布在  Shell
关注(0)|答案(1)|浏览(187)

我试图在Powershell中使用Select-String从这个字符串中获取Chromedriver的第一个序列号,但正则表达式返回了所有内容:'\d{1,4}.\d{1,4}.\d{1,4}.\d{1,4}'。
正则表达式在regex 101和regexr中运行良好,我一直在查看其他Powershell正则表达式示例,甚至是这个guide。但是shell返回整个字符串

'{"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}

字符串
为什么不返回第一个序列号“115.0.5790.170”?
原始字符串可以找到here。。

zaqlnxep

zaqlnxep1#

正则表达式工作正常,只是缺少了匹配值的展开:

'{"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

字符串
退一步说,当你有一个有效的Json字符串时,没有理由使用正则表达式,使用ConvertFrom-Json,然后你可以使用点表示法:

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

相关问题