无法将多行正则表达式与 Powershell 匹配(但它在 C# 中有效)

Unable to match a multiline regex with Powershell (but it does work in C#)

鉴于:

PS D:\tmp> cat ..txt
<abc xyz="1"
     def="xx">
  xaxa
</abc>
<abc xyz="a">
PS D:\tmp>

我在尝试什么:

PS D:\tmp> cat ..txt | sls  '(?m:)<abc[^>]+>'

<abc xyz="a">


PS D:\tmp> cat ..txt | sls  '(?m:)<abc(?:[^>]|$)+>'

<abc xyz="a">


PS D:\tmp> cat ..txt | sls  '(?m:)<abc(?:[^>]|$)+>'

<abc xyz="a">


PS D:\tmp>

现在我知道所有三个变体在普通 C# 中都按预期工作。例如:

PS D:\tmp> [Text.RegularExpressions.Regex]::Matches($(cat 1.txt), '(?m:)<abc[^>]+>')


Groups   : {<abc xyz="1"      def="xx">}
Success  : True
Captures : {<abc xyz="1"      def="xx">}
Index    : 0
Length   : 27
Value    : <abc xyz="1"      def="xx">

Groups   : {<abc xyz="a">}
Success  : True
Captures : {<abc xyz="a">}
Index    : 42
Length   : 13
Value    : <abc xyz="a">



PS D:\tmp>

所以,我很好奇 - 我在纯 Powershell 中做错了什么导致它不起作用?

两件事:

您目前正在将一组字符串传送到 Select-String,它会一个一个地处理它们。使用 Get-Content -Raw.

更改此设置

其次,您需要使用 Select-String 指定 -AllMatches 开关以获取两个实例:

PS C:\> Get-Content ..txt -Raw |Select-String '(?m:)<abc[^>]+>' -AllMatches |Select -Expand Matches

Groups   : {<abc xyz="1"
                def="xx">}
Success  : True
Captures : {<abc xyz="1"
                def="xx">}
Index    : 0
Length   : 27
Value    : <abc xyz="1"
                def="xx">

Groups   : {<abc xyz="a">}
Success  : True
Captures : {<abc xyz="a">}
Index    : 42
Length   : 13
Value    : <abc xyz="a">