gpt4 book ai didi

regex - Perl 可选捕获组不起作用?

转载 作者:行者123 更新时间:2023-12-04 13:05:46 26 4
gpt4 key购买 nike

我有以下 sample.txt 文件:

2021-10-07 10:32:05,767 ERROR [LAWT2] blah.blah.blah - Message processing FAILED: <ExecutionReport blah="xxx" foo="yyy" SessionID="kkk" MoreStuff="zz"> Total time for which application threads were stopped: 0.0003858 seconds, Stopping threads took: 0.0000653 seconds
2021-10-07 10:31:32,902 ERROR [LAWT6] blah.blah.blah - Message processing FAILED: <NewOrderSingle SessionID="zkx" TargetSubID="ttt" Account="blah" MsgType="D" BookingTypeOverride="0" Symbol="6316" OtherField1="othervalue1" Otherfield2="othervalue2"/></D></NewOrderSingle>

我只想获取两个关键字段:“SessionID”和“MsgType”并像这样打印:

SessionID="kkk"|
SessionID="zkx"|MsgType="D"

换句话说:如果组匹配不存在,我只想打印空白。

我尝试了以下方法但没有成功:

$$ perl -ne '/ (SessionID=".*?")? .*(MsgType=".*?")? / and print "$1|$2\n"' sample.txt
SessionID="kkk"|
SessionID="zkx"|

有人能给我讲讲吗?非常感谢。

最佳答案

你可以使用

perl -ne '/\h(SessionID="[^"]*")?(?:\h++.*(MsgType="[^"]*"))?\h/ and print "$1|$2\n"' 

参见 regex demo . 详细信息:

  • \h - 水平空格
  • (SessionID="[^"]*")? - 第 1 组:可选的 SessionID=" 以外的任何零个或多个字符,然后是 "
  • (?:\h++.*(MsgType=".*?"))? - 一个可选的(但贪婪的)序列
    • \h++ - 一个或多个水平空格
    • .* - 尽可能多的除换行符以外的任何零个或多个字符
    • (MsgType="[^"]*") - 第 2 组:SessionID="" 以外的任何零个或多个字符>,然后是 "
  • \h - 水平空格。

参见 online demo :

s='2021-10-07 10:32:05,767 ERROR [LAWT2] blah.blah.blah - Message processing FAILED: <ExecutionReport blah="xxx" foo="yyy" SessionID="kkk" MoreStuff="zz"> Total time for which application threads were stopped: 0.0003858 seconds, Stopping threads took: 0.0000653 seconds
2021-10-07 10:31:32,902 ERROR [LAWT6] blah.blah.blah - Message processing FAILED: <NewOrderSingle SessionID="zkx" TargetSubID="ttt" Account="blah" MsgType="D" BookingTypeOverride="0" Symbol="6316" OtherField1="othervalue1" Otherfield2="othervalue2"/></D></NewOrderSingle>'
perl -ne '/\h(SessionID=".*?")?(?:\h++.*(MsgType=".*?"))?\h/ and print "$1|$2\n"' <<< "$s"

这打印:

SessionID="kkk"|
SessionID="zkx"|MsgType="D"

关于regex - Perl 可选捕获组不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69542971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com