无法将多行正则表达式与Powershell匹配(但它确实在C#中工作)

时间:2021-06-04 00:36:21

Given:

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

What I was trying:

我在尝试什么:

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

<abc xyz="a">


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

<abc xyz="a">


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

<abc xyz="a">


PS D:\tmp>

Now I know all the three variants work as expected in plain C#. For example:

现在我知道所有这三个变体在普通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>

So, I am curious - what am I doing wrong in pure Powershell that it does not work?

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

1 个解决方案

#1


0  

Two things:

You're currently piping an array of strings to Select-String, and it'll process them one by one. Change this by using Get-Content -Raw.

您当前正在将一个字符串数组连接到Select-String,它将逐个处理它们。使用Get-Content -Raw更改此设置。

Secondly, you need to specify the -AllMatches switch with Select-String to get both instances:

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

PS C:\> Get-Content .\1.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">

#1


0  

Two things:

You're currently piping an array of strings to Select-String, and it'll process them one by one. Change this by using Get-Content -Raw.

您当前正在将一个字符串数组连接到Select-String,它将逐个处理它们。使用Get-Content -Raw更改此设置。

Secondly, you need to specify the -AllMatches switch with Select-String to get both instances:

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

PS C:\> Get-Content .\1.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">