Get all possible matches for regex (in python)?

前端 未结 3 1090
难免孤独
难免孤独 2020-12-18 16:17

I have a regex that can match a string in multiple overlapping possible ways. However, it seems to only capture one possible match in the string, how can I get all possible

3条回答
  •  温柔的废话
    2020-12-18 16:31

    No problem:

    >>> regex = "([^-]*-)(?=([^-]*))"
    >>> for result in re.finditer(regex, "foo-foobar-foobaz"):
    >>>     print("".join(result.groups()))
    foo-foobar
    foobar-foobaz
    

    By putting the second capturing parenthesis in a lookahead assertion, you can capture its contents without consuming it in the overall match.

    I've also used [^-]* instead of .* because the dot also matches the separator - which you probably don't want.

提交回复
热议问题