How to get the "longest possible" match with Python's RE module?
fakeaddress at nowhere.org
Wed Sep 13 03:29:02 CEST 2006
Licheng Fang wrote:
> Basically, the problem is this:
>>>> p = re.compile("do|dolittle")
> Python's NFA regexp engine trys only the first option, and happily
> rests on that. There's another example:
>>>> p = re.compile("one(self)?(selfsufficient)?")
> The Python regular expression engine doesn't exaust all the
> possibilities, but in my application I hope to get the longest possible
> match, starting from a given point.
> Is there a way to do this in Python?
Yes. Here's a way, but it sucks real bad:
def longest_match(re_string, text):
regexp = re.compile('(?:' + re_string + ')$')
m = regexp.match(text)
text = text[:-1]
More information about the Python-list