【发布时间】:2014-11-28 18:22:06
【问题描述】:
为什么我会在此函数的结果中得到提取“True”或“False”(当我想要返回的只是邮政编码时):
Function GetZipCodeFromKeyword([String] $keyword)
{
$pattern = "\d{5}"
$keyword -match $pattern
$returnZipcode = "ERROR"
#Write-Host "GetZipCodeFromKeyword RegEx `$Matches.Count=$($Matches.Count)"
if ($Matches.Count -gt 0)
{
$returnZipcode = $Matches[0]
}
Write-Host "`$returnZipcode=$returnZipcode"
return $returnZipcode
}
cls
$testKeyword = "Somewhere in 77562 Texas "
$zipcode = GetZipCodeFromKeyword $testKeyword
Write-Host "Zip='$zipcode' from keyword=$testKeyword"
Write-Host " "
$testKeyword = "Somewhere in Dallas Texas "
$zipcode = GetZipCodeFromKeyword $testKeyword
Write-Host "Zip='$zipcode' from keyword=$testKeyword"
运行时间结果:
$returnZipcode=77562
Zip='True 77562' from keyword=Somewhere in 77562 Texas
$returnZipcode=12345
Zip='False 12345' from keyword=Somewhere in Dallas Texas
【问题讨论】:
-
因为 $keyword -match $pattern = True
-
return并不意味着您认为它在 powershell 中的含义。见stackoverflow.com/questions/10286164/…
标签: regex powershell hashtable