问题
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.
回答1:
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]
回答2:
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.
回答3:
There are overloads of the static [Regex]::Match() method that allow to provide the desired [RegexOptions]
programmatically:
# You can combine several options by doing a bitwise or:
$options = [Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [Text.RegularExpressions.RegexOptions]::CultureInvariant
# or by letting casting do the magic:
$options = [Text.RegularExpressions.RegexOptions]'IgnoreCase, CultureInvariant'
$match = [regex]::Match($input, $regex, $options)
回答4:
You can also include (?i)
in your regex, like so (cmatch forces case sensitive match):
PS H:\> 'THISISSOMETHING' -cmatch 'something'
False
PS H:\> 'THISISSOMETHING' -cmatch '(?i)something'
True
来源:https://stackoverflow.com/questions/12977338/pass-regex-options-to-powershell-regex-type