我如何找到两个子字符串('123STRINGabc' -> '字符串')之间的字符串?

我现在的方法是这样的:

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

然而,这似乎非常低效且不符合python规则。有什么更好的方法来做这样的事情吗?

忘了说: 字符串可能不是以start和end开始和结束的。他们可能会有更多的字符之前和之后。


当前回答

您可以简单地使用这段代码或复制下面的函数。全都整齐地排在一条线上。

def substring(whole, sub1, sub2):
    return whole[whole.index(sub1) : whole.index(sub2)]

如果按照如下方式运行该函数。

print(substring("5+(5*2)+2", "(", "("))

你可能会得到这样的输出:

(5*2

而不是

5*2

如果您希望在输出的末尾有子字符串,代码必须如下所示。

return whole[whole.index(sub1) : whole.index(sub2) + 1]

但如果不希望子字符串在末尾,则+1必须在第一个值上。

return whole[whole.index(sub1) + 1 : whole.index(sub2)]

其他回答

这是我之前在Daniweb中发布的代码片段:

# picking up piece of string between separators
# function using partition, like partition, but drops the separators
def between(left,right,s):
    before,_,a = s.partition(left)
    a,_,after = a.partition(right)
    return before,a,after

s = "bla bla blaa <a>data</a> lsdjfasdjöf (important notice) 'Daniweb forum' tcha tcha tchaa"
print between('<a>','</a>',s)
print between('(',')',s)
print between("'","'",s)

""" Output:
('bla bla blaa ', 'data', " lsdjfasdj\xc3\xb6f (important notice) 'Daniweb forum' tcha tcha tchaa")
('bla bla blaa <a>data</a> lsdjfasdj\xc3\xb6f ', 'important notice', " 'Daniweb forum' tcha tcha tchaa")
('bla bla blaa <a>data</a> lsdjfasdj\xc3\xb6f (important notice) ', 'Daniweb forum', ' tcha tcha tchaa')
"""

如果你不想导入任何东西,试试字符串方法.index():

text = 'I want to find a string between two substrings'
left = 'find a '
right = 'between two'

# Output: 'string'
print(text[text.index(left)+len(left):text.index(right)])
from timeit import timeit
from re import search, DOTALL


def partition_find(string, start, end):
    return string.partition(start)[2].rpartition(end)[0]


def re_find(string, start, end):
    # applying re.escape to start and end would be safer
    return search(start + '(.*)' + end, string, DOTALL).group(1)


def index_find(string, start, end):
    return string[string.find(start) + len(start):string.rfind(end)]


# The wikitext of "Alan Turing law" article form English Wikipeida
# https://en.wikipedia.org/w/index.php?title=Alan_Turing_law&action=edit&oldid=763725886
string = """..."""
start = '==Proposals=='
end = '==Rival bills=='

assert index_find(string, start, end) \
       == partition_find(string, start, end) \
       == re_find(string, start, end)

print('index_find', timeit(
    'index_find(string, start, end)',
    globals=globals(),
    number=100_000,
))

print('partition_find', timeit(
    'partition_find(string, start, end)',
    globals=globals(),
    number=100_000,
))

print('re_find', timeit(
    're_find(string, start, end)',
    globals=globals(),
    number=100_000,
))

结果:

index_find 0.35047444528454114
partition_find 0.5327825636197754
re_find 7.552149639286381

在这个例子中,Re_find几乎比index_find慢20倍。

从Nikolaus Gradwohl的答案进一步,我需要从下面的文件内容(文件名:docker- composition .yml)中获得版本号(即0.0.2)之间('ui:'和'-'):

    version: '3.1'
services:
  ui:
    image: repo-pkg.dev.io:21/website/ui:0.0.2-QA1
    #network_mode: host
    ports:
      - 443:9999
    ulimits:
      nofile:test

这是它如何为我工作(python脚本):

import re, sys

f = open('docker-compose.yml', 'r')
lines = f.read()
result = re.search('ui:(.*)-', lines)
print result.group(1)


Result:
0.0.2

这本质上是cji的答案——7月30日10日5:58。 我更改了try except结构,以便更清楚地说明导致异常的原因。

def find_between( inputStr, firstSubstr, lastSubstr ):
'''
find between firstSubstr and lastSubstr in inputStr  STARTING FROM THE LEFT
    http://stackoverflow.com/questions/3368969/find-string-between-two-substrings
        above also has a func that does this FROM THE RIGHT   
'''
start, end = (-1,-1)
try:
    start = inputStr.index( firstSubstr ) + len( firstSubstr )
except ValueError:
    print '    ValueError: ',
    print "firstSubstr=%s  -  "%( firstSubstr ), 
    print sys.exc_info()[1]

try:
    end = inputStr.index( lastSubstr, start )       
except ValueError:
    print '    ValueError: ',
    print "lastSubstr=%s  -  "%( lastSubstr ), 
    print sys.exc_info()[1]

return inputStr[start:end]