re.sub(): replace longest match instead of leftmost match?

John Gordon gordon at panix.com
Fri Dec 16 16:06:06 EST 2011


In <mailman.3742.1324058429.27778.python-list at python.org> Ian Kelly <ian.g.kelly at gmail.com> writes:

> >>> I'm also looking for a regexp that will remove leading zeroes in each
> >>> four-digit group, but will leave a single zero if the group was all
> >>> zeroes.

> pattern = r'\b0{1,3}([1-9a-f][0-9a-f]*|0)\b'
> re.sub(pattern, r'\1', string, flags=re.IGNORECASE)

Perfect.  Thanks Ian!

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon at panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"




More information about the Python-list mailing list