is there a way find substring index through a regular expression in python?
-
29-09-2019 - |
Question
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?
Solution
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
OTHER TIPS
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.
regular expression "re" package should be of help
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow