[Python] Find string between two substrings

取出兩個字串之間的值。

方案1:(不建議使用)

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

輸出結果:iwantthis


方案2:(有點神奇)

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

方案3:

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

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *