gpt4 book ai didi

regex - 在 Powershell Regeg -match 之后从 $matches 哈希表中提取数据

转载 作者:行者123 更新时间:2023-12-04 10:38:43 25 4
gpt4 key购买 nike

我已经花了一个多小时试图让一个简单的 RegEx 工作。我的模式正在运行,我正在取回 $Matches,正如我所读到的,它应该是一个哈希表。那么我如何获得我捕获的内容?

代码:

   cls 
$keyword = "this is a 12345 test"
$pattern = "\d{5}"
$keyword -match $pattern
$returnZipcode = "ERROR"
Write-Host "GetZipCodeFromKeyword RegEx `$Matches.Count=$($Matches.Count)"
$Matches | Out-String | Write-Host
Write-Host "`$Matches[0].Value=$($Matches[0].Value)"
Write-Host "`$Matches.Get_Item('0')=$($Matches.Get_Item("0"))"
if ($Matches.Count -gt 0)
{
$returnZipcode = $Matches[0].Value
}

# this is how hash tables work - why doesn't same work with the $Matches variable?
$states = @{"Washington" = "Olympia"; "Oregon" = "Salem"; California = "Sacramento"}
$states | Out-String | Write-Host
Write-Host "`$states.Get_Item('Oregon')=$($states.Get_Item("Oregon"))"

运行时结果:
Name                           Value  
---- -----
0 12345

$Matches[0].Value=
$Matches.Get_Item('0')=

Name Value
---- -----
Washington Olympia
Oregon Salem
California Sacramento

$states.Get_Item('Oregon')=Salem

最佳答案

$Matches只是一个哈希表,NameValue列不是元素的属性。 Name只是关键,Value是值(value)。

PS C:\> $Matches

Name Value
---- -----
0 12345


PS C:\> $Matches[0]
12345

如果您愿意,可以使用 Get_Item , 但 key 在 $Matches是一个整数,而不是一个字符串:
PS C:\> $states.Get_Item('Oregon')
Salem
PS C:\> $Matches.Get_Item(0)
12345

与其他一些语言不同,并非所有哈希表键都必须是字符串,除非您告诉它,否则 Powershell 通常不会将数字与字符串相互转换。

关于regex - 在 Powershell Regeg -match 之后从 $matches 哈希表中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27193956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com