首先将您的 JSON 表示为字符串:
$myjson = @'
{
"Name": "AllZones_APOPreface_GeographyMatch_FromBRE_ToSTR",
"Sequence": 0,
"Condition": "this.TripOriginLocationCode==\"BRE\"&&this.TripDestinationLocationCode==\"STR\"",
"Action": "this.FeesRate=0.19m;this.ZoneCode=\"Zone1\";halt",
"ElseAction": ""
}
'@
接下来,创建一个匹配 \" 和 \" 之间所有内容的正则表达式,长度小于 10 个字符(否则它将匹配不需要的结果)。
$regex = [regex]::new('\\"(?<content>.{1,10})\\"')
接下来,通过在正则表达式上调用Matches() 方法来执行正则表达式比较。将您的 JSON 字符串作为您要执行比较的文本传递到方法参数中。
$matchlist = $regex.Matches($myjson)
最后,获取在正则表达式中定义的content 匹配组,并从中提取值。
$matchlist.Groups.Where({ $PSItem.Name -eq 'content' }).Value
结果
BRE
STR
Zone1
方法 #2:使用 Regex Look-behinds 进行更准确的匹配
这是一个更具体的正则表达式,它使用后视来适当地验证每个字段。然后我们将每个匹配项分配给开发人员友好的变量名称。
$regex = [regex]::new('(?<=TripOriginLocationCode==\\")(?<OriginCode>\w+)|(?<=TripDestinationLocationCode==\\")(?<DestinationCode>\w+)|(?<=ZoneCode=\\")(?<ZoneCode>\w+)')
$matchlist = $regex.Matches($myjson)
### Assign each component to its own friendly variable name
$OriginCode, $DestinationCode, $ZoneCode = $matchlist[0].Value, $matchlist[1].Value, $matchlist[2].Value
### Construct a string from the individual components
'Your origin code is {0}, your destination code is {1}, and your zone code is {2}' -f $OriginCode, $DestinationCode, $ZoneCode
结果
Your origin code is BRE, your destination code is STR, and your zone code is Zone1