Powershell: match operator returns true but $matches is null

RegexPowershell

Regex Problem Overview


I am working with a regex to match file contents:

> (get-content $_) -match $somePattern
the line of text that matches the pattern

this returns true, a match, however my $matches variable remains null.

> $matches -eq $null
True

Shouldn't $matches have the match groups in it?

Regex Solutions


Solution 1 - Regex

Strictly speaking string -match ... and collection -match ... are two different operators. The first gets a Boolean value and fills $matches. The second gets each collection item that matches a pattern and apparently does not fill $matches.

Your example should work as you expect if the file contains a single line (the first operator works). If a file contains 2+ lines then the second operator is used and $matches is not set.

The same is true for other Boolean operators applied to a collection. That is collection -op ... returns items where item -op ... is true.

Examples:

1..10 -gt 5 # 6 7 8 9 10
'apple', 'banana', 'orange' -match 'e' # apple, orange 

Boolean operators applied to collections are handy if used properly. But they may be confusing as well and lead to easy to make mistakes:

$object = @(1, $null, 2, $null)

# "not safe" comparison with $null, perhaps a mistake
if ($object -eq $null) {
    '-eq gets @($null, $null) which is evaluated to $true by if!'
}

# safe comparison with $null
if ($null -eq $object) {
    'this is not called'
}

Another example with -match and -notmatch may look confusing:

$object = 'apple', 'banana', 'orange'

if ($object -match 'e') {
    'this is called'
}

if ($object -notmatch 'e') {
    'this is also called, because "banana" is evaluated to $true by if!'
}

Solution 2 - Regex

I had the same problem, and the exact lines were working from the Powershell command prompt but not from Powershell ISE or a normal command prompt. If you don' want to cycle through all the lines of the file one by one using foreach, you can simply convert that to a string like this and it should work then:

if([string](Get-Content -path $filePath) -match $pattern)
{
   $matches[1]
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthew BonigView Question on Stackoverflow
Solution 1 - RegexRoman KuzminView Answer on Stackoverflow
Solution 2 - RegexPiyush SoniView Answer on Stackoverflow