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

Joh*_*ard 206 python string substring

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

我目前的方法是这样的:

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

然而,这似乎是非常低效和非pythonic.做这样的事情有什么更好的方法?

忘记提及:字符串可能无法以start和开头和结尾end.他们之前和之后可能会有更多的角色.

Nik*_*ohl 265

import re

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

  • 如果我需要在 2 个子字符串之间查找,并且第二个子字符串在第一个子字符串之后重复,该怎么办?像这样的东西: s= 'asdf=5;I_WANT_ONLY_THIS123jasdNOT_THIS123jasd (6认同)
  • 添加 `?` 使其非贪婪 `result = re.search('asdf=5;(.*?)123jasd', s)` (3认同)

cji*_*cji 146

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" )
Run Code Online (Sandbox Code Playgroud)

得到:

123STRING
STRINGabc
Run Code Online (Sandbox Code Playgroud)

我认为应该注意 - 根据你需要的行为,你可以混合indexrindex调用或使用上述版本之一(它相当于正则表达式(.*)(.*?)组).

  • 他说他想要一种更像Pythonic的方式,而这显然不那么重要.我不确定为什么选择这个答案,即使OP自己的解决方案更好. (34认同)
  • +1,因为在多次找到“end”的情况下,它比其他解决方案效果更好。但我确实同意OP的解决方案更简单。 (3认同)
  • 同意。我会使用@Tim McNamara 的解决方案,或者类似“start+test+end in substring”的建议 (2认同)

小智 69

start = 'asdf=5;'
end = '123jasd'
s = 'asdf=5;iwantthis123jasd'
print s[s.find(start)+len(start):s.rfind(end)]
Run Code Online (Sandbox Code Playgroud)

iwantthis
Run Code Online (Sandbox Code Playgroud)

  • 我赞成这一点,因为无论输入字符串大小如何,它都可以工作。其他一些方法假设您提前知道长度。 (4认同)
  • 是的,它可以在没有输入大小的情况下工作,但是它确实假设字符串存在 (2认同)

Tim*_*ara 48

s[len(start):-len(end)]
Run Code Online (Sandbox Code Playgroud)

  • 假设start和end始终位于字符串的开头和结尾,这非常好.否则,我可能会使用正则表达式. (9认同)
  • 我对我能想到的原始问题进行了最恐怖的回答.使用`in`运算符进行测试可能比regexp更快. (2认同)

Tim*_*ara 32

字符串格式化为Nikolaus Gradwohl建议提供了一些灵活性.start并且end根据需要,现在可以修改.

import re

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

result = re.search('%s(.*)%s' % (start, end), s).group(1)
print(result)
Run Code Online (Sandbox Code Playgroud)

  • 我得到这个:`'NoneType' 对象没有属性 'group'` (2认同)

reu*_*ano 16

只需将OP自己的解决方案转换为答案:

def find_between(s, start, end):
  return (s.split(start))[1].split(end)[0]
Run Code Online (Sandbox Code Playgroud)

  • 如果您将其他人的解决方案作为您自己的解决方案,您可能应该将其作为社区Wiki. (5认同)

Joh*_*ooy 12

这是一种方法

_,_,rest = s.partition(start)
result,_,_ = rest.partition(end)
print result
Run Code Online (Sandbox Code Playgroud)

另一种使用regexp的方法

import re
print re.findall(re.escape(start)+"(.*)"+re.escape(end),s)[0]
Run Code Online (Sandbox Code Playgroud)

要么

print re.search(re.escape(start)+"(.*)"+re.escape(end),s).group(1)
Run Code Online (Sandbox Code Playgroud)


小智 11

source='your token _here0@df and maybe _here1@df or maybe _here2@df'
start_sep='_'
end_sep='@df'
result=[]
tmp=source.split(start_sep)
for par in tmp:
  if end_sep in par:
    result.append(par.split(end_sep)[0])

print result
Run Code Online (Sandbox Code Playgroud)

必须显示:here0,here1,here2

正则表达式更好,但它需要额外的lib,你可能只想去python


Fer*_*ann 10

如果您不想导入任何内容,请尝试使用字符串方法.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)]
Run Code Online (Sandbox Code Playgroud)

  • 我很喜欢它。简单,单行,足够清晰,无需额外导入,开箱即用。我不知道上面过度设计的答案有什么关系。 (4认同)
  • 好。像在[edit](https://stackoverflow.com/revisions/51456576/2)中所做的那样,添加一个简单的描述可以帮助新用户更好地理解您的答案。在使帖子变得更好之后,您可以将要求这样做的所有评论标记为** _不再需要。_**,因此主持人将其删除。这样的评论被视为噪音。阅读后将其删除并标记。感谢您使SO成为更好的地方。:) (2认同)
  • 这并不是检查“正确”文本是否实际上位于文本的右侧。如果文本前面出现任何“right”,则它将不起作用。 (2认同)

Mny*_*kka 6

这是我所做的一个函数,用于返回一个列表,其中包含搜索到的 string1 和 string2 之间的字符串。

def GetListOfSubstrings(stringSubject,string1,string2):
    MyList = []
    intstart=0
    strlength=len(stringSubject)
    continueloop = 1

    while(intstart < strlength and continueloop == 1):
        intindex1=stringSubject.find(string1,intstart)
        if(intindex1 != -1): #The substring was found, lets proceed
            intindex1 = intindex1+len(string1)
            intindex2 = stringSubject.find(string2,intindex1)
            if(intindex2 != -1):
                subsequence=stringSubject[intindex1:intindex2]
                MyList.append(subsequence)
                intstart=intindex2+len(string2)
            else:
                continueloop=0
        else:
            continueloop=0
    return MyList


#Usage Example
mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","y68")
for x in range(0, len(List)):
               print(List[x])
output:


mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","3")
for x in range(0, len(List)):
              print(List[x])
output:
    2
    2
    2
    2

mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","y")
for x in range(0, len(List)):
               print(List[x])
output:
23
23o123pp123
Run Code Online (Sandbox Code Playgroud)


Rei*_* SE 5

要提取STRING,请尝试:

myString = '123STRINGabc'
startString = '123'
endString = 'abc'

mySubString=myString[myString.find(startString)+len(startString):myString.find(endString)]
Run Code Online (Sandbox Code Playgroud)