Powershell-仅打印引号之间的文本?

Powershell-仅打印引号之间的文本?,powershell,Powershell,如何使以下文本的输出仅显示引号中的文本(不带引号) “示例文本” 变成: apple orange blood orange 理想情况下,如果可能的话,我希望用一行程序来完成。我认为它是带-match的正则表达式,但我不确定。这里有一种方法 $text='this is an "apple". it is red this is an "orange". it is orange this is an "blood orange". it is reddish' $text.split("`

如何使以下文本的输出仅显示引号中的文本(不带引号)

“示例文本”

变成:

apple
orange
blood orange
理想情况下,如果可能的话,我希望用一行程序来完成。我认为它是带-match的正则表达式,但我不确定。

这里有一种方法

$text='this is an "apple". it is red
this is an "orange". it is orange
this is an "blood orange". it is reddish'

$text.split("`n")|%{
$_.split('"')[1]
}
这是成功的解决方案

$text='this is an "apple". it is red
this is an "orange". it is orange
this is an "blood orange". it is reddish'

$text|%{$_.split('"')[1]}

只是使用regex的另一种方法:

appcmd list apppool | % { [regex]::match( $_ , '(?<=")(.+)(?=")' ) } | select -expa value

appcmd-list-apppool |%{[regex]::match($),(?基于.NET方法的简明解决方案,使用PSv3+语法:

$str = @'
this is an "apple". it is red
this is an "orange". it is orange
this is an "blood orange". it is reddish
'@

[regex]::Matches($str, '".*?"').Value -replace '"'
Regex
“*?”
匹配
“…”
-包含的标记和
.matches()
返回所有标记;
.Value
提取它们,并
-replace'
删除
字符

这意味着上述操作甚至可以在每行使用多个
“…”
令牌(尽管请注意,使用嵌入式转义
字符提取令牌(例如,
\”
)将不起作用)


只有在以下情况下,才可以使用
-match
运算符(仅查找一个匹配项):

  • 将输入拆分为行
  • 并且每行最多包含1个
    “…”
    标记(这对于问题中的示例输入是正确的)
以下是一个PSv4+解决方案:

# Split string into lines, then use -match to find the first "..." token
($str -split "`r?`n").ForEach({ if ($_ -match '"(.*?)"') { $Matches[1] } })  
自动变量
$Matches
包含上一次
-match
操作的结果(如果LHS是标量),索引
[1]
包含第一个(也是唯一一个)捕获组(
(…)
)匹配的内容


如果
-match
有一个名为
-matchall
的变体,那么它会很方便,这样就可以编写:

# WISHFUL THINKING (as of PowerShell Core 6.2)
$str -matchall '".*?"' -replace '"'

请参见GitHub。

我尝试了这一点,但收到了一个错误:在$text.split('n')|%{(不包含名为'split'的方法)上,抱歉,它确实有效。但是,解决方案略有不同,因为$text有两个撇号(一个在开头,一个在结尾)。在我的文本示例中,没有撇号。没有撇号可以吗?@MikeJ但如何获取文本?是否使用获取内容?在本例中,是$text=appcmd list apppooltry直接拆分$text:$text |%{$|.split('“)[1]}谢谢你的正则表达式,我喜欢它。但是你不觉得它有点干净吗?语义在这一点上,因为它们都工作,但我更喜欢更干净的解决方案。这取决于人们如何知道正则表达式语法…无论如何,我发布了我的答案,因为你提到了正则表达式…Spli这是一个很好的解决方案!
# Split string into lines, then use -match to find the first "..." token
($str -split "`r?`n").ForEach({ if ($_ -match '"(.*?)"') { $Matches[1] } })  
# WISHFUL THINKING (as of PowerShell Core 6.2)
$str -matchall '".*?"' -replace '"'