Odd behavior with regex-based operators and case sensitivity

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.

Advertisements

About Dave Wyatt

Microsoft MVP (PowerShell), IT professional.
This entry was posted in PowerShell and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s