在不使用正向预查的情况下,可以使用循环和条件判断来匹配两组字符之间的字符串。以下是一个示例代码:
import re
def match_between_strings(text, start, end):
matches = []
start_index = 0
while True:
start_pos = text.find(start, start_index)
if start_pos == -1:
break
start_pos += len(start)
end_pos = text.find(end, start_pos)
if end_pos == -1:
break
matches.append(text[start_pos:end_pos])
start_index = end_pos + len(end)
return matches
text = "Hello [world], [how] are [you] doing?"
start = "["
end = "]"
matches = match_between_strings(text, start, end)
print(matches)
该代码定义了一个match_between_strings
函数,该函数接受三个参数:text
表示要搜索的文本,start
表示开始字符串,end
表示结束字符串。函数通过循环和条件判断来匹配start
和end
之间的字符串。在每次循环中,使用text.find()
函数来查找start
和end
的位置,如果找到了,就将匹配的字符串添加到matches
列表中。然后更新start_index
以继续搜索下一个匹配。
在示例代码中,将搜索字符串设为"Hello [world], [how] are [you] doing?",开始字符串设为"[",结束字符串设为"]",最终输出结果为['world', 'how', 'you']
,即匹配到的字符串列表。