我想在 Powershell 中使用这个使用 gis 标志的正则表达式,
https://regex101.com/r/yoM4cV/1
/(?<=#start)(.+)(?=#end)/gis
Run Code Online (Sandbox Code Playgroud)
匹配 #start 和 #end 之间的句子
#start
hello powershell regex
what is the equivalent of flags gis
#end
Run Code Online (Sandbox Code Playgroud)
我找不到任何有关 Powershell 的 gis 标志支持的信息。Powershell 中缺少这个吗?如果是,有什么替代方案?
更新:我问是因为这返回 false
$test=@'
#start
hello powershell regex
what is the equivalent of flags gis
#end
'@
$test -match (?<=#start)(.+)(?=#end)
Run Code Online (Sandbox Code Playgroud)
要修复您的示例,您需要这样编写:
\n$test -match \'(?s)(?<=#start)(.+)(?=#end)\'\nRun Code Online (Sandbox Code Playgroud)\n(?s)以允许.匹配多行。()是因为 PowerShell 分组运算符在您的示例中使 PowerShell 尝试将正则表达式模式解释为 PowerShell 表达式,但这不起作用。相反,将其作为文字字符串传递给-match.详细解释:
\n从 开始gis,只有i(不区分大小写)和s(单行)可用作 PowerShell 中的标志(或者更常见的是在 .NET 中,因为 PowerShell 在后台使用 .NET RegEx 支持)。
您可以将它们指定为模式开头的内联标志...
\n(?is)(?<=#start)(.+)(?=#end)\nRun Code Online (Sandbox Code Playgroud)\n...或者通过使用接受参数的类options的参数:RegexRegExOptions
$options = [System.Text.RegularExpressions.RegexOptions] \'IgnoreCase, Singleline\'\n[Regex]::Match(\'text\', \'pattern\', $options)\nRun Code Online (Sandbox Code Playgroud)\ng(全局)标志不能直接使用。您可以通过调用该方法来有效地使用它[Regex]::Matches(),该方法查找所有匹配项(与[Regex]::Match()仅-match查找第一个匹配项的 and 运算符相反)。它的输出是已找到的所有匹配项的集合。
或者,您可以使用Select-String参数-AllMatches,如Wiktor Stribi\xc5\xbcew\ 的答案所示。
出于演示目的,我稍微修改了您的示例,以便它实际上找到多个匹配项(您的原始正则表达式匹配第一个#start到最后一个之间的所有内容#end,因此它只找到一个匹配项)。
$text = @\'\n#start\nhello powershell regex\nwhat is the equivalent of flags gis\n#end\n#start\nfoobar\n#end\n\'@\n\n$pattern = \'(?is)(?<=#start)(.+?)(?=#end)\'\n\nforeach( $match in [Regex]::Matches($text, $pattern) ) {\n \'----- Match -----\'\n $match.Groups[1].Value # Output the captured value of the 1st group\n}\nRun Code Online (Sandbox Code Playgroud)\n输出:
\n----- Match -----\n\nhello powershell regex\nwhat is the equivalent of flags gis\n\n----- Match -----\n\nfoobar\nRun Code Online (Sandbox Code Playgroud)\n