I happened to be browsing the PowerShell reddit page this evening, and came across a very interesting post: RegEx -NotMatch Isn’t Ignoring Case. I spent some time playing around with these operators for a bit, and came up with several scenarios in which the results might not match the case-sensitivity behavior when you use -imatch or -cmatch. (-notmatch, -replace and -split also have similar oddities in some circumstances.)
I posted a bug report here, where you can find repro code if you’re interested. The PowerShell team may take action and change this behavior at some point, but for the time being, just avoid doing two things:
- Don’t pass an actualy [regex] object to these operators for your pattern; just pass in a string and let PowerShell construct the Regex for you behind the scenes. If you pass in a [regex], that object’s case sensitivity behavior may kick in (even if it doesn’t match the expected behavior of the operator you’re using.
- Don’t pass in a pattern with an embedded regex option to control case-sensitivity. This will override the operator’s behavior. For example: (‘TEST’ -imatch ‘test’) will be true, and (‘TEST’ -imatch ‘(?-i)test’) will be false.
If you don’t do either of those things, then the -match, -notmatch, -replace, and -split operators (and their case-sensitive versions) should always behave the way you expected them to.