Search code examples
powershellmatchmultiple-matches

Powershell -match returning System.Collections.Hashtable[1] in $Matches


I haven't the faintest what is going on here, so I am turning it over to the cloud mind to figure out, sorry.

I have a string (confirmed with .gettype()), an excerpt of which is below (\r\n at the end of each line):

Request Inputs
Inputs With Value
Displaying 17 out of 19 inputs
Company Division
<my company name>

However when run against the below pattern, cannot figure out why it produces System.Collections.Hastable[1] in $Matches[1]. And the main thing, it is empty. Why?

$TextBoxText -match '(?s).*(?:Company Division[\r\n])([^\r\n]*)'

Solution

  • Assuming you're wondering why your current pattern didn't capture <my company name> in the capturing group 1, the reason is because in Windows, the strings new lines will usually be CRLF and with your current character class [\r\n] you're allowing both, CR and LF, but only a single match of any of them. So you could do:

    if ($TextBoxText -match '(?s).*Company Division[\r\n]{1,2}([^\r\n]*)') {
        $Matches[1] # <my company name>
    }
    

    Then the pattern works fine, but even better would be to use \r?\n which would also work well in any OS:

    if ($TextBoxText -match '(?s).*Company Division\r?\n([^\r\n]*)') {
        $Matches[1] # <my company name>
    }
    

    In both cases the non-capturing group can be removed, there is no reason to have it there. You could also remove (?s).* from the pattern, leaving it for now as it's unclear what was the intent. If you're only interested in capturing what comes after Company Division, then the pattern could just be:

    if ($TextBoxText -match '(?<=Company Division\r?\n)[^\r\n]*') {
        $Matches[0] # <my company name>
    }