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

我现在的方法是这样的:

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

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

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


当前回答

s[len(start):-len(end)]

其他回答

从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

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

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

这对我来说似乎更直接:

import re

s = 'asdf=5;iwantthis123jasd'
x= re.search('iwantthis',s)
print(s[x.start():x.end()])

字符串格式为Nikolaus Gradwohl的建议增加了一些灵活性。开始和结束现在可以根据需要进行修改。

import re

s = 'asdf=5;iwantthis123jasd'
start = 'asdf=5;'
end = '123jasd'

result = re.search('%s(.*)%s' % (start, end), s).group(1)
print(result)

我的方法是,

find index of start string in s => i
find index of end string in s => j

substring = substring(i+len(start) to j-1)