1

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

regular expression "re" package should be of help

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.