Ted Striker
Ted Striker

Reputation: 81

Can a re.finditer() instance fail to match the original pattern?

a. Is there a situation where the code below will cause an AssertionError?

b. If so, how do I prevent that?

def finditer_test(pattern, string, flags=0):
    for match_object in re.finditer(pattern, string, flags):
        assert re.match(pattern, match_object.group(0), flags)

Upvotes: 2

Views: 131

Answers (2)

cardel
cardel

Reputation: 66

Yes, it can fail, for example when the pattern contains lookahead assertions.

Check finditer_test(r'a(?=b)', 'abc')

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336188

Yes, that's possible - for example if the regex uses lookaround assertions that look beyond the edges of the match itself:

(?<= )bar(?= )

will match bar in "foo bar baz", but not in "bar" (which would be group(0)).

Upvotes: 1

Related Questions