Message 29112 - Python tracker (original) (raw)
Using sre.sub[n], an "unmatched group" error can occur.
The test I used is this pattern:
sre.sub("foo(?:b(ar)|baz)","\1","foobaz")
This will cause the following backtrace to occur:
Traceback (most recent call last): File "", line 1, in ? File "lib/python2.4/sre.py", line 142, in sub return _compile(pattern, 0).sub(repl, string, count) File "lib/python2.4/sre.py", line 260, in filter return sre_parse.expand_template(template, match) File "lib/python2.4/sre_parse.py", line 782, in expand_template raise error, "unmatched group" sre_constants.error: unmatched group
Python Version 2.4.3, Mac OS X (behaviour has been verified on Windows 2.4.3 as well).
This behaviour, while by design, is unwanted because this type of matching usually requests that a blank match be returned (i.e. the example should return '')
The example that I was trying resembles the following:
sre.sub("User: (?:Registered User #(\d+)|Guest)","%USERID|\1%",data)
The intended behaviour is that the function returns "" when the user is a guest and the user number if the user is a registered member.
However, when this function encounters a Guest, it raises an exception and terminates, which is not what is wanted.
Perl and other regex engines behave as I have described, substituting empty strings for unmatched groups. The code fix is relatively simple, and would really help out for these types of things.