|
82 | 82 |
|
83 | 83 | # Combining characters; issue #7518 |
84 | 84 | assert not re.match(r"\w", "\u0345"), r"\w should not match U+0345 (category Mn)" |
| 85 | + |
| 86 | + |
| 87 | +def test_findall_group_that_did_not_participate(): |
| 88 | + # findall returns the matched text, not a match object, so a group that |
| 89 | + # took no part in the match stands in as an empty value of the type the |
| 90 | + # pattern works on. One group used to come back as None, and a bytes |
| 91 | + # pattern used to mix str into its results. |
| 92 | + assert re.findall(r"(a)?b", "b ab") == ["", "a"] |
| 93 | + assert re.findall(r"(x)?", "a") == ["", ""] |
| 94 | + assert re.findall(r"(a|b)?c", "c ac bc") == ["", "a", "b"] |
| 95 | + assert re.findall(r"(?P<g>a)?b", "b ab") == ["", "a"] |
| 96 | + assert re.compile(r"(a)?b").findall("b ab") == ["", "a"] |
| 97 | + |
| 98 | + assert re.findall(rb"(a)?b", b"b ab") == [b"", b"a"] |
| 99 | + assert re.findall(rb"(x)?", b"a") == [b"", b""] |
| 100 | + |
| 101 | + # Two or more groups give a tuple per match, with the same stand-in. |
| 102 | + assert re.findall(r"(a)|(b)", "ab") == [("a", ""), ("", "b")] |
| 103 | + assert re.findall(rb"(a)|(b)", b"ab") == [(b"a", b""), (b"", b"b")] |
| 104 | + assert re.findall(rb"(a)(b)?", b"a ab") == [(b"a", b""), (b"a", b"b")] |
| 105 | + |
| 106 | + # The type is the pattern's, never the other one. |
| 107 | + assert [type(x) for x in re.findall(r"(a)?b", "b ab")] == [str, str] |
| 108 | + assert [type(x) for x in re.findall(rb"(a)?b", b"b ab")] == [bytes, bytes] |
| 109 | + assert [type(y) for x in re.findall(rb"(a)|(b)", b"ab") for y in x] == [ |
| 110 | + bytes, |
| 111 | + bytes, |
| 112 | + bytes, |
| 113 | + bytes, |
| 114 | + ] |
| 115 | + |
| 116 | + # A group that does participate, and no group at all, are unchanged. |
| 117 | + assert re.findall(r"(a)", "aa") == ["a", "a"] |
| 118 | + assert re.findall(r"a", "aa") == ["a", "a"] |
| 119 | + assert re.findall(rb"a", b"aa") == [b"a", b"a"] |
| 120 | + |
| 121 | + # A match object still reports None, which is where the difference lies. |
| 122 | + assert re.match(r"(a)?b", "b").groups() == (None,) |
| 123 | + assert re.match(r"(a)?b", "b").group(1) is None |
| 124 | + assert [m.groups() for m in re.finditer(r"(a)?b", "b ab")] == [(None,), ("a",)] |
| 125 | + assert re.split(r"(a)|(b)", "xaybz") == ["x", "a", None, "y", None, "b", "z"] |
| 126 | + |
| 127 | + |
| 128 | +test_findall_group_that_did_not_participate() |
0 commit comments