Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

regex - Powershell: match operator returns true but $matches is null

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!'
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...