如何查看RegexOptions枚举中可用的选项?

Bil*_*ore 4 regex powershell enums

如何使用powershell脚本中的此函数来使用-cmatch运算符执行不区分大小写的匹配:

static System.Text.RegularExpressions.Match Match(
     string input, 
     string pattern,
     System.Text.RegularExpressions.RegexOptions options)
Run Code Online (Sandbox Code Playgroud)

我在想它是这样的:

PS>  $input = "one two three"

PS>  $m = [regex]::Match($input, "one", ????)
Run Code Online (Sandbox Code Playgroud)

我有一个问题的部分是????上面的.

您如何看待System.Text.RegularExpressions.RegexOptionsPowerShell提示中提供的内容以及在上面的代码中使用它的语法是什么?

bri*_*ist 6

查看枚举中可用选项的简单"作弊"方法是在PowerShell提示符或ISE中使用制表符完成.首先,[System.Text.RegularExpressions.RegexOptions]::然后使用CTRL SPACE(或TAB)查看选项.

程序化的方式,因为RegexOptions是一个枚举,是这样的:

[System.Enum]::GetNames([System.Text.RegularExpressions.RegexOptions])
Run Code Online (Sandbox Code Playgroud)

当您需要在PowerShell中传递枚举值时,您可以传递长格式的完全限定枚举值(这是我的首选):

[System.Text.RegularExpressions.RegexOptions]::IgnoreCase
Run Code Online (Sandbox Code Playgroud)

或者你可以直接传递数值(1),或者你可以传递一个字符串,它将与枚举的文本值匹配'IgnoreCase'.

对于您的实际问题:使用[regex]::Match()已经区分大小写.您可以直接转[System.Text.RegularExpressions.RegexOptions]::None接到您的电话(或0,或'None').

如果您希望它不区分大小写,那么您可以使用IgnoreCase上面的枚举值.

因为这种类型的枚举是一系列位标志,所以你可以将它们组合起来.为此,您使用-bor(按位或,或二进制或)运算符:

$myOptions = [System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor 
        [System.Text.RegularExpressions.RegexOptions]::SingleLine -bor
        [System.Text.RegularExpressions.RegexOptions]::IgnorePatternWhitespace
Run Code Online (Sandbox Code Playgroud)

但是,PowerShell方便地将字符串强制转换为枚举并不止于单个值.正如mklement0提醒我的那样,你可以用逗号分隔字符串中的枚举名称,PowerShell 仍会正确解析它.

因此,'IgnoreCase, SingleLine, IgnorePatternWhitespace'当您需要传入时,可以直接使用字符串RegexOptions.你也可以预先投射它:

$myOptions = 'IgnoreCase, SingleLine, IgnorePatternWhitespace' -as [System.Text.RegularExpressions.RegexOptions]
$myOptions = [System.Text.RegularExpressions.RegexOptions]'IgnoreCase, SingleLine, IgnorePatternWhitespace'
Run Code Online (Sandbox Code Playgroud)