本文介绍了为什么 Perl 正则表达式 \K 不排除 \K 之前匹配的模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 test.txt 的文件,内容如下:

>上次登录: Mon Jul 13 05:09:33 2020 您有邮件.>**********************************>猫,你刚刚登录机器sampleserver2>**********************************>>-------------------------------------------------------------->|要稍后切换环境,请运行: |>||>|改变 |>||>-------------------------------------------------------------->>>当前目录 =>/apps/users/cat Oracle SID:示例>猫@sampleserver2:

我尝试运行下面的命令只返回最后一个冒号,但它返回整行.据我了解,它应该只返回 : 而不是 cat@sampleserver2:.我究竟做错了什么?我也在使用一个应该能够处理这个问题的 Perl 版本.

cat test.txt |perl -ne '打印/.+@.+\K:/'猫@sampleserver2:
% perl -v这是 perl 5, version 30, subversion 1 (v5.30.1) 为x86_64-linux-ld
解决方案

你可能想说:

perl -ne 'print $&if/.+@.+\K:/' test.txt

输出:

:

  • 语句print if CONDITION 等价于print $_ if CONDITION,如果条件满足,则只打印没有修改的行.请改用 $&.
  • 第二个参数 cat@sampleserver2: 将导致错误提示无法打开 cat@sampleserver2:: 没有这样的文件或目录."

I have a file called test.txt with the following:

> Last login: Mon Jul 13 05:09:33 2020 You have mail.   
> ******************************
> cat, you have just logged into machine sampleserver2    
> ******************************
> 
> --------------------------------------------------------------  
> | To switch environments later, run:                         |
> |                                                            |
> | change                                                     |
> |                                                            |
> --------------------------------------------------------------
> 
> 
> Current Dir => /apps/users/cat     Oracle SID: SAMPLE
> cat@sampleserver2:

I try running the command below to only return the last colon but it returns the full line. To my understanding it should only be returning the : and not cat@sampleserver2:. What am I doing wrong? I'm also using a version of Perl that should be able to handle this.

cat test.txt | perl -ne 'print if /.+@.+\K:/'
cat@sampleserver2:
% perl -v 
This is perl 5, version 30, subversion 1 (v5.30.1) built for
x86_64-linux-ld
解决方案

You may want to say:

perl -ne 'print $& if /.+@.+\K:/' test.txt

which outputs:

:

  • The statement print if CONDITION is equivalent to print $_ if CONDITION and just prints the line without modifications if the CONDITION meets.Please use $& instead.
  • The second argument cat@sampleserver2: will cause an error saying"Can't open cat@sampleserver2:: No such file or directory."

这篇关于为什么 Perl 正则表达式 \K 不排除 \K 之前匹配的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 15:33