4

I've already spent over an hour trying to get a simple RegEx to work. My pattern is working, and I'm getting back the $Matches which as I have read is supposed to be a hash table. So how do I get what I've captured?

Code:

   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"))"

Run time results:

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

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

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

$states.Get_Item('Oregon')=Salem
NealWalters
  • 17,197
  • 42
  • 141
  • 251

1 Answers1

3

$Matches is just a hashtable, the Name and Value columns aren't properties of the elements. Name is just the key, Value is the value.

PS C:\> $Matches

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


PS C:\> $Matches[0]
12345

If you wish you can use Get_Item, but the key in $Matches is an integer, not a string:

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

Unlike some other languages not all hashtable keys have to be strings and Powershell mostly won't convert numbers to and from strings unless you tell it to.

Duncan
  • 92,073
  • 11
  • 122
  • 156
  • Thanks, just posted follow-up here: http://stackoverflow.com/questions/27194148/powershell-match-in-function-gets-extra-true-false-when-returned I thought the true/false was coming back as part of hashtable, still not sure why. – NealWalters Nov 28 '14 at 18:22