re.sub(): replace longest match instead of leftmost match?
John Gordon
gordon at panix.com
Fri Dec 16 16:04:49 EST 2011
In <mailman.3737.1324054637.27778.python-list at python.org> Devin Jeanpierre <jeanpierreda at gmail.com> writes:
> 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=3Dlambda m: (m.end() =3D m.start()))
I ended up doing something similar:
# find the longest match
longest_match = ''
for word in re.findall('((0000:?)+)', ip6):
if len(word[0]) > len(longest_match):
longest_match = word[0]
# if we found a match, replace it with a colon
if longest_match:
ip6 = re.sub(longest_match, ':', ip6, 1)
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"
More information about the Python-list
mailing list