如何在一个长字符串中搜索值?

问题描述 投票:0回答:1

我目前正在尝试从通过cURL命令使用GET请求获得的长字符串中过滤值。输出看起来像这样:

{"errors":null,"result":{"host_id":"1632","display_name":"notshownhere","hostname":"notshownhere","dnsname":"","ip":"1.1.1.1","host_type_id":"1","checks":[{"check_id":"12851","preset_id":"1","checktype_id":"1","checktype_short_name":"ping","status":"3","status_condition":"ok","status_color":"green","status_change_time":"1589066121","result_short":"1.1.1.1 is alive","result_time":"1591683892"}

我的目标是从此输出中过滤掉host_id。这意味着,我想找到一种方法,仅输出数字为host_id1632

我尝试了Select-String,但由于字符串太长而无法使用。

string powershell filter select-string
1个回答
0
投票

这看起来像JSON,最好在适当的JSON上使用ConvertFrom-Json命令。这将生成一个PowerShell对象,您可以在其中使用object.'host_id'来检索值。

解析字符串,您可以执行以下操作。

# Assuming $j contains your string
($j | Select-String -Pattern '(?<="host_id":")\d+(?=")').Matches.Value

由于-pattern默认情况下使用正则表达式字符串,因此(?<=)包含从当前位置开始的正向后视。 (?=)是积极的前瞻。 \d+是一个或多个数字。由于命令返回了MatchInfo对象,因此您需要访问Value以返回数字。

© www.soinside.com 2019 - 2024. All rights reserved.