将正则表达式选项传递给PowerShell [regex]类型

mis*_*kin 4 regex powershell case-insensitive

我使用以下正则表达式代码捕获两个匹配的组:

[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
Run Code Online (Sandbox Code Playgroud)

我的问题是我想让它不区分大小写,我不想使用正则表达式修饰符.

我知道你可以在.NET中传递正则表达式选项,但我无法弄清楚如何使用PowerShell做同样的事情.

arg*_*nym 12

静态[Regex]::Match()方法的重载允许以[RegexOptions]编程方式提供所需的内容:

# 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)
Run Code Online (Sandbox Code Playgroud)


Sha*_*evy 5

请改用 PowerShell 的 -match 运算符。默认情况下不区分大小写:

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

对于区分大小写的匹配,请使用 -cmatch。


aqu*_*nas 5

请尝试使用-match.例如,

$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]
Run Code Online (Sandbox Code Playgroud)