基于.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 '"'
正则表达式 ".*?" 匹配 "..."-enclosed 标记,.Matches() 返回所有标记; .Value 提取它们,-replace '"' 去除 " 字符。
这意味着上述内容甚至可以使用 multiple "..." 每行标记(但请注意,使用 embedded escaped " 字符提取标记。(例如,@ 987654333@) 不起作用)。
使用-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] 包含第一个(也是唯一一个)捕获组(@ 987654340@) 匹配。
如果-match 有一个名为-matchall 的变体会很方便,这样人们就可以这样写:
# WISHFUL THINKING (as of PowerShell Core 6.2)
$str -matchall '".*?"' -replace '"'
请参阅 GitHub 上的 this feature suggestion。