Reputation: 163
I'm new to PowerShell scripting, and I am puzzled by some behaviour I have encountered.
I have been following examples to learn how to use matching and had seen some examples where [regex] was put in front of a string. I had assumed (perhaps wrongly) that this is a cast, explicitly specifying that the object is a regular expression. But it seems that using [regex] changes the case sensitivity of the resulting match:
PS > $array = 'ABC','DEF','GHI'
PS > $array -match 'DEF'
DEF
PS > $array -match 'def'
DEF
PS > $array -match [regex]'def'
PS > $array -match [regex]'DEF'
DEF
What is actually going on, here? What is the [regex] doing, that results in case sensitivity?
Upvotes: 0
Views: 1683
Reputation: 31
Because I don't have enough reputation to comment to add to @Ansgar Wiechers answer, I will answer here to also note if you want to ignore case when casting [regex] from .NET, you can prefix your pattern with (?i) which is a mode modifier (case insensitivity). Here is a good resource where you can check out the available mode modifiers (there's a lot).
So, PS > $array -match [regex]'(?i)def'
would return true.
Upvotes: 0
Reputation: 200463
[regex]'def'
is casting the string to a Regex
object, which is case-sensitive by default. PowerShell regular expressions on the other hand are case-insensitive by default.
PS C:\> ('def').GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
PS C:\> ([regex]'def').GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Regex System.Object
Upvotes: 3
Reputation: 30293
The $array -match
calls are case-insensitive by default.
Adding the [regex]
keyword initiates a regular expressions search, and regular expressions are by default case-sensitive. That's all.
Upvotes: 1