Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Input 1:

Event: Started Flapping

Regex 1:

^Event: (\S+ Flapping)

Output 1:

Started Flapping

Input 2:

Event: CRIT -> OK

Regex 2:

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

Ouput 2:

OK

The Regex i tried
(?:^Event:\s+\S+\s+\S+\s+(?P<service>\S+)$|^Event: (?P<flap>Started Flapping)|((?P=service)|(?P=flap)))

>Solution :

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
  • \s+ – one or more whitespaces
  • (?| – 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+) – Group 1: one or more non-whitespaces
  • | – or
    • (Started Flapping) – Group 1: Started Flapping fixed string
  • ) – end of the branch reset group
  • $ – end of string.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading