【发布时间】:2014-11-28 18:05:59
【问题描述】:
我已经花了一个多小时试图让一个简单的 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
【问题讨论】:
标签: regex powershell hashtable