gpt4 book ai didi

Python如何找到两个子字符串之间的字符串列表?

转载 作者:行者123 更新时间:2023-12-01 05:00:02 25 4
gpt4 key购买 nike

我正在尝试获取两个字符串之间的字符串列表

text = """
something = $/I want to get this string A:blah blah
somethingB = ($/I want to get this string as well B:blah blah blah)
"""

#I had this working to get the first found string
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 ""


find_between(text, '$/', ':')
# Result: I want to get this string A #

但我希望能够搜索字符串并获得一个列表,找到......类似的东西

['I want to get this string A', 'I want to get this string as well B']

最佳答案

为什么不使用 re模块(正则表达式)来做什么?

------------------------------------------------------------ ---------- 解决方案:1 -------------------------------------- ----------------------

演示 repl.it

代码:

import re

text = """
something = $/I want to get this string A:blah blah
somethingB = ($/I want to get this string as well B:blah blah blah)
"""

found = re.findall(r'\$\/(.+?)\:', text)
print found

输出:

['I want to get this string A', 'I want to get this string as well B']

正则表达式解释:

r'\$\/(.+?):'

\$: This will match $(This character needs to be escaped).
\/: This will match /(This character needs to be escaped).
( : This represents the beginning of extraction.
. : This will match any character except a new line.
+ : This represents match 1 or more previous character.
? : This will do a non-greedy search.
) : This represents the end of extraction.
: : This will match :.

------------------------------------------------------------ ---------- 解决方案:2 -------------------------------------- ----------------------

演示 repl.it

代码:

import re

text = """
something = $/I want to get this string A:blah blah
somethingB = ($/I want to get this string as well B:blah blah blah)
"""

def findBetween(first, second):
first = '\\' + first[0] + '\\' + first[1]
found = re.findall(r'' + first + '(.+?)' + second, text)
print found

findBetween('$/', ':')

输出:

['I want to get this string A', 'I want to get this string as well B']

关于Python如何找到两个子字符串之间的字符串列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26458504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com