1

我想找到一个子字符串的索引位置,但是子字符串很长并且难以表达(多行,甚至你需要转义它)所以我想使用正则表达式来匹配它们,并返回子字符串的索引,函数就像str.find 或 str.rfind ,是否有一些包帮助?

4

3 回答 3

1

.start()对成功匹配的结果对象(所谓的匹配对象)使用方法:

 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.

于 2011-06-09T09:32:39.530 回答
0

正则表达式“re”包应该有帮助

于 2010-10-12T03:09:28.583 回答
0

像这样的东西可能会起作用:

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'])

然后:

>>> index('bar', 'foo') is None
True
>>> index('barfoo', 'foo')
3
>>> index('\xbarfoo', 'foo')
2
于 2010-10-12T04:22:49.343 回答