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

Devin Jeanpierre jeanpierreda at gmail.com
Fri Dec 16 11:56:32 EST 2011


You could use re.finditer to find the longest match, and then replace
it manually by hand (via string slicing).

(a match is the longest if (m.end() - m.start()) is the largest --
so, max(re.finditer(...), key=lambda m: (m.end() = m.start()))

-- Devin

P.S. does anyone else get bothered by how it's slice.start and
slice.stop, but match.start() and match.end() ?

On Fri, Dec 16, 2011 at 11:49 AM, John Gordon <gordon at panix.com> wrote:
> According to the documentation on re.sub(), it replaces the leftmost
> matching pattern.
>
> However, I want to replace the *longest* matching pattern, which is
> not necessarily the leftmost match.  Any suggestions?
>
> I'm working with IPv6 CIDR strings, and I want to replace the longest
> match of "(0000:|0000$)+" with ":".  But when I use re.sub() it replaces
> the leftmost match, even if there is a longer match later in the string.
>
> 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.
>
> Thanks!
>
> --
> 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"
>
> --
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list