regexpowershellcase-insensitive

Pass regex options to PowerShell [regex] type


I capture two groups matched using the regexp code below:

[regex]$regex = "^([0-9]{1,20})(b|kb|mb|gb|tb)$"

$matches = $regex.match($minSize)

$size=[int64]$matches.Groups[1].Value
$unit=$matches.Groups[2].Value

My problem is I want to make it case-insensitive, and I do not want to use regex modifiers.

I know you can pass regex options in .NET, but I cannot figure out how to do the same with PowerShell.


Solution

  • Try using -match instead. E.g.,

    $minSize = "20Gb"
    $regex = "^([0-9]{1,20})(b|kb|mb|gb|tb)$"
    $minSize -match $regex #Automatic $Matches variable created
    $size=[int64]$Matches[1]
    $unit=$Matches[2]