Reputation: 14691
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?
Upvotes: 1
Views: 692
Reputation: 66709
regular expression "re" package should be of help
Upvotes: 0
Reputation: 23516
Use the .start()
method on the result object of a successful match (the so called match object):
mo = re.search('foo', veryLongString)
if mo:
return mo.start()
If the match was successful, mo.start()
will give you the (first) index of the matching substring within the searched string.
Upvotes: 1
Reputation: 16615
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
Upvotes: 0