【问题标题】:Extracting data from the $matches hashtable after a Powershell Regeg -match在 Powershell Regex -match 之后从 $matches 哈希表中提取数据
【发布时间】: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


    【解决方案1】:

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

    PS C:\> $Matches
    
    Name                           Value
    ----                           -----
    0                              12345
    
    
    PS C:\> $Matches[0]
    12345
    

    如果您希望可以使用Get_Item,但$Matches 中的键是整数,而不是字符串:

    PS C:\> $states.Get_Item('Oregon')
    Salem
    PS C:\> $Matches.Get_Item(0)
    12345
    

    与其他一些语言不同,并非所有哈希表键都必须是字符串,而且 Powershell 大多不会将数字与字符串转换,除非你告诉它。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2012-02-19
    相关资源
    最近更新 更多