In Python, how to parse a string representing a set of keyword arguments such that the order does not matter

后端 未结 2 740
走了就别回头了
走了就别回头了 2021-01-18 11:59

I\'m writing a class RecurringInterval which - based on the dateutil.rrule object - represents a recurring interval in time. I have defined a custom, human-read

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 12:40

    You have many options here, each with different downsides.

    One approach would be to use a repeated alternation, like (by weekday|by month)*:

    (?PWeekly)?\s+from (?P.+?)\s+till (?P.+?)(?:\s+by weekday (?P.+?)|\s+by month (?P.+?))*$
    

    This will match strings of the form week month and month week, but also week week or month week month etc.

    Another option would be use lookaheads, like (?=.*by weekday)?(?=.*by month)?:

     (?PWeekly)?\s+from (?P.+?)\s+till (?P.+?(?=$| by))(?=.*\s+by weekday (?P.+?(?=$| by))|)(?=.*\s+by month (?P.+?(?=$| by))|)
    

    However, this requires a known delimiter (I used " by") to know how far to match. Also, it'll silently ignore any extra characters (meaning it'll match strings of the form by weekday [some gargabe] by month).

提交回复
热议问题