Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]*)'
like image 913
user66001 Avatar asked Oct 16 '25 16:10

user66001


1 Answers

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 add a {1,2} quantifier allowing 1 or 2 matches of any, then your pattern should work well:

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

However, an even better approach would be to use \r?\n (an optional CR followed by a LF). This way your pattern works well in any OS.

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

In both cases the non-capturing group ((?:...)) and (?s).* can be removed, there is no apparent reason to have them.

Since you're only interested in capturing what comes after Company Division, then you could also use a positive-lookbehind ((?<=...)) and remove the current capturing group 1, then you can get the match via $Matches[0]:

if ($TextBoxText -match '(?<=Company Division\r?\n)[^\r\n]*') {
    $Matches[0] # <my company name>
}
like image 119
Santiago Squarzon Avatar answered Oct 18 '25 12:10

Santiago Squarzon