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

时间:2013-01-28 18:00:05

标签: powershell

如何让以下文字的输出只显示引号中的文字(不带引号)?

示例文字“

this is an "apple". it is red
this is an "orange". it is orange
this is an "blood orange". it is reddish

变为:

apple
orange
blood orange

理想情况下,如果可能的话,我想在一个班轮内完成。我认为这是-match的正则表达式,但我不确定。

3 个答案:

答案 0 :(得分:3)

使用正则表达式的另一种方式:

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

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

答案 1 :(得分:2)

这是一种方式

$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]}

答案 2 :(得分:0)

基于.NET方法[regex]::Matches()的简洁解决方案,使用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 '"'

正则表达式".*?"与包含"..."的令牌匹配,.Matches()返回所有令牌; .Value提取它们,然后-replace '"'剥离"个字符。

这意味着以上代码甚至可以每行使用多个 "..."个令牌(尽管请注意,提取带有嵌入式转义的 "个字符的令牌。 (例如\")无效。


使用-match运算符-仅查找 a (一个)匹配项-仅在 时使用

  • 您将输入分为
  • ,并且每行最多包含 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上的this feature suggestion