简体   繁体   English

Perl 正则表达式在捕获组一中返回命名组

[英]Perl Regex return named groups in capture Group one

I try to get a regex which returns the match in the first capture group.我尝试获取一个正则表达式,它返回第一个捕获组中的匹配项。

The Application where I put the regex in can only use the first capture Group.我放入正则表达式的应用程序只能使用第一个捕获组。

Each regex on it's own is working, but i can't combine these two in a way that the output is always in the first capture group每个正则表达式都在工作,但我不能将这两个组合在一起,使 output 始终在第一个捕获组中

Input 1:输入 1:

Event: Started Flapping

Regex 1:正则表达式 1:

^Event: (\S+ Flapping)

Output 1: Output 1:

Started Flapping

Input 2:输入 2:

Event: CRIT -> OK

Regex 2:正则表达式 2:

^Event:\s+\S+\s+\S+\s+(\S+)

Ouput 2:输出 2:

OK

The Regex i tried (?:^Event:\s+\S+\s+\S+\s+(?P<service>\S+)$|^Event: (?P<flap>Started Flapping)|((?P=service)|(?P=flap)))我试过的正则表达式(?:^Event:\s+\S+\s+\S+\s+(?P<service>\S+)$|^Event: (?P<flap>Started Flapping)|((?P=service)|(?P=flap)))

You can use a branch reset group :您可以使用 分支重置组

^Event:\s+(?|\S+\s+\S+\s+(\S+)|(Started Flapping))$
# or, to factor in \S+\s+:
^Event:\s+(?|(?:\S+\s+){2}(\S+)|(Started Flapping))$

See the regex demo .请参阅正则表达式演示 Details :详情

  • ^ - start of string ^ - 字符串的开头
  • Event: - a fixed string Event: - 固定字符串
  • \s+ - one or more whitespaces \s+ - 一个或多个空格
  • (?| - start of a branch reset group: (?| - 分支重置组的开始:
    • \S+\s+\S+\s+ - two occurrences of one or more non-whitespaces followed with one or more whitespaces \S+\s+\S+\s+ - 两次出现一个或多个非空格,后跟一个或多个空格
    • (\S+) - Group 1: one or more non-whitespaces (\S+) - 第 1 组:一个或多个非空格
  • | - or - 或者
    • (Started Flapping) - Group 1: Started Flapping fixed string (Started Flapping) - 第 1 组: Started Flapping固定琴弦
  • ) - end of the branch reset group ) - 分支重置组结束
  • $ - end of string. $ - 字符串结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM