[Tutor] RE module is working ?

Peter Otten __peter__ at web.de
Fri Feb 4 11:15:12 CET 2011


Karim wrote:

> Recall:
> 
>  >>> re.subn(r'([^\\])?"', r'\1\\"', expression)
> 
> Traceback (most recent call last):
>      File "<stdin>", line 1, in<module>
>      File "/home/karim/build/python/install/lib/python2.7/re.py", line
> 162, in subn
>        return _compile(pattern, flags).subn(repl, string, count)
>      File "/home/karim/build/python/install/lib/python2.7/re.py", line
> 278, in filter
>        return sre_parse.expand_template(template, match)
>      File "/home/karim/build/python/install/lib/python2.7/sre_parse.py",
> line 787, in expand_template
>        raise error, "unmatched group"
> sre_constants.error: unmatched group
> 
> 
> Found the solution: '?' needs to be inside parenthesis (saved pattern)
> because outside we don't know if the saved match argument
> will exist or not namely '\1'.
> 
>  >>> re.subn(r'([^\\]?)"', r'\1\\"', expression)
> 
> (' \\"\\" ', 2)
> 
> sed unix command is more permissive: sed 's/\([^\\]\)\?"/\1\\"/g'
> because '?' can be outside parenthesis (saved pattern but escaped for
> sed). \1 seems to not cause issue when matching is found. Perhaps it is
> created only when match occurs.

Thanks for reporting the explanation.



More information about the Tutor mailing list