Please help me fix my regex :).
Summary: How can I make a repeating group (tags) match greedily even if it means a preceding optional group (a label) is empty.
For some reason, my regex is not acting as desired:
code: re.match("^foo(-.*?)?((?:-(?:a|b))*)$", "foo-a-b").groups() output: ('-a', '-b') expected: ('', '-a-b') # since "-a" and "-b" are both tags that should be greedily matched by the last pattern
Examples of expected behavior:
Input | Expected | Current Output | Notes |
---|---|---|---|
foo-a-b | ('', '-a-b') | ('-a', '-b') | everything after "foo" is a tag, so label should be empty |
foo-b-a | ('', '-b-a') | ('-b', '-a') | everything after "foo" is a tag, so label should be empty |
foo-c-a-b | ('-c', '-a-b') | as expected | has both a label and a tag |
foo-a-b-c | ('-a-b-c', '') | as expected | everything is a label because tags can only be at the end |
My real-life problem has a much more complicated definition of tags, labels, and "foo", but the issue is reproducible even with this smaller contrived example.
Thanks in advance!
https://stackoverflow.com/questions/66937068/regex-optional-text-followed-by-greedily-matched-repeating-text April 04, 2021 at 08:36AM
没有评论:
发表评论