查找两个子字符串之间的字符串

400 投票
20 回答
818396 浏览
提问于 2025-04-16 02:03

我该如何在两个子字符串之间找到一个字符串(比如说从'123STRINGabc'中提取出'STRING')呢?

我现在的方法是这样的:

>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis

不过,这样做似乎效率不高,也不太符合Python的风格。有没有更好的方法来实现这个功能呢?

我忘了提一点:这个字符串可能并不是以startend开头和结尾的,它们前面和后面可能还有其他字符。

20 个回答

142
start = 'asdf=5;'
end = '123jasd'
s = 'asdf=5;iwantthis123jasd'
print s[s.find(start)+len(start):s.rfind(end)]

给出

iwantthis
185
s = "123123STRINGabcabc"

def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

def find_between_r( s, first, last ):
    try:
        start = s.rindex( first ) + len( first )
        end = s.rindex( last, start )
        return s[start:end]
    except ValueError:
        return ""


print find_between( s, "123", "abc" )
print find_between_r( s, "123", "abc" )

给出的结果是:

123STRING
STRINGabc

我觉得需要说明的是——根据你需要的行为,你可以混合使用 indexrindex 的调用,或者选择上面提到的某个版本(这相当于正则表达式中的 (.*)(.*?) 组)。

510
import re

s = 'asdf=5;iwantthis123jasd'
result = re.search('asdf=5;(.*)123jasd', s)
print(result.group(1))

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答