简体   繁体   中英

Why are [regex] match() and -match different?

I was playing around with regex in PowerShell when I stumbled across a strange scenario differing Powershell's [regex] class match with -match . In the case that I was attempting to remove empty lines from a string, when using -replace none of my expressions worked while with [regex] replace() removed the lines perfectly fine.

PS C:\Users\Neko> $a = @"
line1

line2
line3

line4
"@
PS C:\Users\Neko> $a -match '\n^\s*$'
false
PS C:\Users\Neko> $b = [regex]::new('\n^\s*$',"IgnoreCase, Multiline")
PS C:\Users\Neko> $b.Matches($a)


Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 5
Length   : 1
Value    :


Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 18
Length   : 1
Value    :

I haven't seen this in any other case that I've tested yet but I have no idea what the differences between the two could be or what is causing these differed results. This is the same with -replace (which makes sense) but I have no idea what may be causing this.


So what are the differences between the PowerShell -match and -replace methods to the .NET regular expression class match() and replace() methods and why are they different?

The key is probably Multiline

$regex = [regex]'\n^\s*$'
$regexM = [regex]::new('\n^\s*$',"IgnoreCase, Multiline")
$a = @"
line1

line2
line3

line4
"@
$a -match $regex
false
$a -match $regexM
true

Also note that actually creating the regex is computationally expensive while running it is not. I recommend assigning all the regex together at the beginning so you only compile them once. It also makes the actual matching more readable (if you pick good names):

$regex = @{
    ExtraWhitespace = [regex]::new('\n^\s*$',"IgnoreCase, Multiline")
}
$a -match $regex.ExtraWhitespace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM