Optional Named Capture group with suffix

Viewed 64

I have a specification of the command

RENAME_SECTION file::section [new_file::]new_section

file, section and new_section are mandatory, new_file is optional.

Than means that all next expressions will match:

RENAME_SECTION io.cfg::BUS1 io.cfg::BUS3
RENAME_SECTION io.cfg::BUS2       io_new.cfg::BUS2
RENAME_SECTION io.cfg::VID VID1

I try to get all provided parameters with Python re.search(pattern, config_line) using the pattern

(?P<command>RENAME_SECTION\s)\s*(?P<file>\S+)::(?P<section>.*)\s+(?P<target_file>\S*)[::]?(?P<target_section>.*)

This pattern match two first cases, but not the third one, the reason is absents of last ::.

How can I bundle :: with target_file named capture group?

2 Answers

You may consider a pattern like

(?P<command>RENAME_SECTION)\s+(?P<file>\S+)::(?P<section>\S+)\s+(?:(?P<target_file>[^\s:]+)::)?(?P<target_section>\S+)

See the regex demo. If you plan to match a whole string with the pattern, add ^ at the start and $ at the end.

Details

  • (?P<command>RENAME_SECTION) - a RENAME_SECTION string
  • \s+ - 1+ whitespaces
  • (?P<file>\S+) - 1+ non-whitespaces
  • :: - a :: substring
  • (?P<section>\S+) - 1+ non-whitespaces
  • \s+ - 1+ whitespaces
  • (?:(?P<target_file>[^\s:]+)::)? - an optional group matching 1 or 0 occurrences of
    • [^\s:]+ - 1+ chars other than whitespace and : chars
    • :: - a :: substring
  • (?P<target_section>\S+) - 1+ non-whitespaces.

You may try this regex with an optional match and anchors:

^(?P<command>RENAME_SECTION)\s+(?P<file>\S+?)::(?P<section>\S+)\s+(?:(?P<target_file>\S+?)::)?(?P<target_section>.+)$

RegEx Demo

(?:(?P<target_file>\S+?)::)? is an optional non-capturing group that makes matching target_file and trailing :: optional.

Related