re.sub and empty groups

Rich Harkins rich at
Tue Feb 12 17:00:31 CET 2002

On Tuesday 12 February 2002 10:56 am, Patrick Gaherty wrote:
> I'm trying something along the following lines:
> line = re.sub(r'(a)(b)?(c)',r'\3\2\1',line)
> and Python complains about empty groups when (b)? doesn't match.
> What's the best way of getting around this?
> Thanks in advance.
> Patrick Gaherty

Try moving the question mark into the group itself, for instance:

>>> print re.sub(r'(a)(b?)(c)',r'\3\2\1','abc')
>>> print re.sub(r'(a)(b?)(c)',r'\3\2\1','ac')

If you need a group where (b?) is you can use the non-grouping group, i.e.: 

This of course assumes that you want to insert nothing for the second group 
when the second group doesn't match.  If you need to insert something 
more complicated I would guess it is time to move to a function for a 
replacement string...

Hope this helps!

More information about the Python-list mailing list