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

Replace regex with captured group ONLY

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

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

或 Perl:

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

所以我希望我的结果是 只是 Some text,否则(意思是如果 </code> 中没有捕获任何东西)那么它应该只是空的。</p> <p>我确实注意到 <strong>perl</strong> 如果 <code>Some text 在 line/string(这让我感到困惑......)。 (还注意到删除 ^$ 没有效果)

基本上,我试图通过 here 讨论的 --only-matching 选项来获得 grep 会 return 的结果。只有我 want/need 在正则表达式中使用 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)/ ?  : ""' list_of_values | cat -n
     1
     2
     3
     4
     5
     6  Some text
     7
     8
     9
    10  Some text

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


你在问为什么

foo Some text bar
012345678901234567

结果只是一个空字符串而不是

Some text

嗯,

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

你可以使用

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

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

简单得多:

$_ = /(Some text)/ ?  : "";

我质疑你对 -p 的使用。您确定要为每行输入输出一行吗?在我看来你更愿意

perl -nle'print  if /(Some text)/'