我如何找到两个子字符串('123STRINGabc' -> '字符串')之间的字符串?
我现在的方法是这样的:
>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis
然而,这似乎非常低效且不符合python规则。有什么更好的方法来做这样的事情吗?
忘了说:
字符串可能不是以start和end开始和结束的。他们可能会有更多的字符之前和之后。
这些解决方案假设起始字符串和最终字符串是不同的。下面是当初始和最终指示符相同时,我用于整个文件的解决方案,假设整个文件是使用readlines()读取的:
def extractstring(line,flag='$'):
if flag in line: # $ is the flag
dex1=line.index(flag)
subline=line[dex1+1:-1] #leave out flag (+1) to end of line
dex2=subline.index(flag)
string=subline[0:dex2].strip() #does not include last flag, strip whitespace
return(string)
例子:
lines=['asdf 1qr3 qtqay 45q at $A NEWT?$ asdfa afeasd',
'afafoaltat $I GOT BETTER!$ derpity derp derp']
for line in lines:
string=extractstring(line,flag='$')
print(string)
给:
A NEWT?
I GOT BETTER!
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
我认为应该注意的是-根据需要的行为,您可以混合使用index和rindex调用,或者使用上述版本之一(它相当于regex(.*)和(.*?)组)。