mlzboy
mlzboy

Reputation: 14691

is there a way find substring index through a regular expression in python?

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

Answers (3)

ThomasH
ThomasH

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

Attila O.
Attila O.

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

Related Questions