仅将正则表达式替换为捕获的组

问题描述 投票:0回答:1

我试图理解为什么以下内容没有给我我认为(或想要:))应该返回的内容:

sed -r 's/^(.*?)(Some text)?(.*)$/\2/' list_of_values

或 Perl:

perl -lpe 's/^(.*?)(Some text)?(.*)$/$2/' list_of_values

所以我希望我的结果是

只是Some text

,否则(意味着如果$2
中没有捕获任何内容)那么它应该是空的。

我确实注意到,对于

perl,如果 Some text 位于行/字符串的开头(这让我感到困惑......),它 does

 可以工作。 (还注意到删除 
^
$
 没有效果)

基本上,我正在尝试获取

grep

 将通过 
--only-matching
 选项返回的内容,如
此处所述。只有我想/需要在正则表达式中使用 sub/replace 。

已编辑(添加示例数据)

输入示例:

$ cat -n list_of_values 1 Black 2 Blue 3 Brown 4 Dial Color 5 Fabric 6 Leather and Some text after that .... 7 Pearl Color 8 Stainless Steel 9 White 10 White Mother-of-Pearl Some text stuff

所需输出:

$ perl -ple '$_ = /(Some text)/ ? $1 : ""' list_of_values | cat -n 1 2 3 4 5 6 Some text 7 8 9 10 Some text
    
regex perl sed regex-group
1个回答
5
投票
首先,

this 展示了如何使用 Perl 复制 grep -o


你问为什么要再次申请

s/^(.*?)(Some text)?(.*)$/$2/


foo Some text bar 012345678901234567
结果只是一个空字符串而不是

Some text
嗯,

    在位置 0,
  • ^
     匹配 0 个字符。
  • 在位置 0,
  • (.*?)
     匹配 0 个字符。
  • 在位置 0,
  • (Some text)?
     匹配 0 个字符。
  • 在位置 0,
  • (.*)
     匹配 17 个字符。
  • 在位置 17,
  • $
     匹配 0 个字符。
  • 匹配成功。
你可以使用

s{^ .*? (?: (Some[ ]text) .* | $ )}{ $1 // "" }xse;

s{^ .*? (?: (Some[ ]text) .* | $ )}{$1}xs; # Warns if warnings are on.
更简单:

$_ = /Some text/ ? $& : "";


我质疑你对

-p

的使用。您确定要为每行输入输出一行吗?在我看来你宁愿拥有

perl -nle'print $& if /Some text/'
    
© www.soinside.com 2019 - 2024. All rights reserved.