re.sub and empty groups

Hugo Ferreira bytter at gmail.com
Tue Jan 16 08:08:35 EST 2007


Hi!

I'm trying to do a search-replace in places where some groups are
optional... Here's an example:

>> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola").groups()
('ola', None)

>> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|").groups()
('ola', '')

>> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|ole").groups()
('ola', 'ole')

The second and third results are right, but not the first one, where
it should be equal to the second (i.e., it should be an empty string
instead of None). This is because I want to use re.sub() and when the
group is None, it blows up with a stack trace...

Maybe I'm not getting the essence of groups and non-grouping groups.
Someone care to explain (and, give the correct solution :)) ?

Thanks in advance,

Hugo Ferreira

-- 
GPG Fingerprint: B0D7 1249 447D F5BB 22C5  5B9B 078C 2615 504B 7B85



More information about the Python-list mailing list