Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 269
mishkin Avatar asked Oct 19 '12 15:10

mishkin


People also ask

What type of regex does PowerShell use?

A regular expression is a pattern used to match text. It can be made up of literal characters, operators, and other constructs. This article demonstrates regular expression syntax in PowerShell. PowerShell has several operators and cmdlets that use regular expressions.

How do you use regex expressions in PowerShell?

PowerShell provides a handy shortcut if you want to use the Regex() constructor that takes a string with your regular expression as the only parameter. $regex = [regex] '\W+' compiles the regular expression \W+ (which matches one or more non-word characters) and stores the result in the variable $regex.

Does PowerShell support regex?

You've learned how to use Select-String to match regex patterns in text but PowerShell also has a few handy operators that support regex. One of the most useful and popular PowerShell regex operators is the match and notmatch operators.

What is Cmatch in PowerShell?

-cmatch makes the operation case sensitive. -notmatch returns true when there is no match. The i and c variants of an operator is available for all comparison operators.


2 Answers

After using [regex] type accelerator, Options property is ReadOnly and can't be changed. But you can call a constructor with RegexOptions parameter:

$regex = [System.Text.RegularExpressions.Regex]::new('^([0-9]{1,20})(b|kb|mb|gb|tb)$','IgnoreCase')

To pass multiple options use bitwise or operator on underlying values:

$regex = [regex]::new('^([0-9]{1,20})(b|kb|mb|gb|tb)$',[System.Text.RegularExpressions.RegexOptions]::Multiline.value__ -bor [System.Text.RegularExpressions.RegexOptions]::IgnoreCase.value__)

But simple addition seems to work, too:

[System.Text.RegularExpressions.RegexOptions]::Multiline + System.Text.RegularExpressions.RegexOptions]::IgnoreCase

It would even work when supplied numeric flag (35 = IgnoreCase=1 + MultiLine=2 + IgnorePatternWhitespace=32), altough relying on enum values directly is usually not a best practice:

$regex = [regex]::new('^([0-9]{1,20})(b|kb|mb|gb|tb)$',36)
$regex.Options
like image 153
AdamL Avatar answered Oct 06 '22 09:10

AdamL


Use PowerShell's -match operator instead. By default it is case-insensitive:

$minSize -match '^([0-9]{1,20})(b|kb|mb|gb|tb)$'

For case-sensitive matches, use -cmatch.

like image 32
Shay Levy Avatar answered Oct 06 '22 07:10

Shay Levy