views:

34

answers:

2

i want to find a substring 's index postion,but the substring is long and hard to expression(multiline,& even you need escape for it ) so i want to use regex to match them,and return the substring's index, the function like str.find or str.rfind , is there some package help for this?

A: 

Something like this might work:

import re

def index(longstr, pat):
    rx = re.compile(r'(?P<pre>.*?)({0})'.format(pat))
    match = rx.match(longstr)
    return match and len(match.groupdict()['pre'])

Then:

>>> index('bar', 'foo') is None
True
>>> index('barfoo', 'foo')
3
>>> index('\xbarfoo', 'foo')
2
Attila Oláh