Home > Mobile >  Regex: how to handle two groups with the same name?
Regex: how to handle two groups with the same name?

Time:03-02

I have strings with some daily times, which are given in two possible ways:

  1. (...) 1100-1300 DAILY (...)
  2. (...) DAILY 1100-1300 (...)

I want to read the time. Unfortunately I cannot do this like below, because I have the same group used twice (which is unacceptable), so this throws an error:

import re

string = "TIME SCHEDULE: 1100-1300 DAILY"
pattern = "((?P<time>\d{4}-\d{4}) DAILY|DAILY (?P<time>\d{4}-\d{4}))"
match = re.search(pattern, string)
time = match.group("time")

What I could do here, is to create two separate groups (time1 and time2), then check if any of them is present in the match... Possible, but dirty and not scalable (what if I had more than 2 groups?).

How can I approach it without use of non-standard modules?

CodePudding user response:

You can tweak your regex to use named capture group only once:

(?P<time>\d{4}-\d{4})(?:(?= DAILY)|(?<=DAILY \d{4}-\d{4}))

RegEx Demo

(?:(?= DAILY)|(?<=DAILY \d{4}-\d{4})) uses an alternation to apply condition of matching DAILY after time or else it uses a lookbehind to ensure presence of DAILY before the time.

  • Related