Python 使用可选的结束模式提取字符串

Python 使用可选的结束模式提取字符串,python,regex,python-3.x,Python,Regex,Python 3.x,我想提取一个子字符串,它可能出现在两个子字符串之间,也可能出现在原始字符串的末尾。起始分隔符是ab,结束分隔符可以是cd或原始字符串的结尾 示例: c = 'ab123:random text1 cd4576:text2' d = 'cd123:text2 ab75589:text1' e = 'ab35:rand text2 cd765:text1' 期望的答案: c = 'random text1' d = 'text1' e = 'rand text2' re.findall('ab\

我想提取一个子字符串,它可能出现在两个子字符串之间,也可能出现在原始字符串的末尾。起始分隔符是
ab
,结束分隔符可以是
cd
或原始字符串的结尾

示例:

c = 'ab123:random text1 cd4576:text2'
d = 'cd123:text2 ab75589:text1'
e = 'ab35:rand text2 cd765:text1'
期望的答案:

c = 'random text1'
d = 'text1'
e = 'rand text2'
re.findall('ab\d+:(.*)', i)
>>> ['random text1 cd4576: text2'], [' text1'], ['rand text2 cd765: text1']

re.findall('^ab\d+:(.*)cd\d+:', i)
>>>['random text1 '], [], ['rand text2 ']
我能够将起始子字符串与
re.findall('ab\d+:(.*),I)
匹配。但当我尝试添加结尾模式时,我找不到想要的答案:

c = 'random text1'
d = 'text1'
e = 'rand text2'
re.findall('ab\d+:(.*)', i)
>>> ['random text1 cd4576: text2'], [' text1'], ['rand text2 cd765: text1']

re.findall('^ab\d+:(.*)cd\d+:', i)
>>>['random text1 '], [], ['rand text2 ']
尝试将或“|”与以下组一起使用:

re.findall('ab[^:]+:[ \t]*(.+)[ \t]*(cd[^:]+|$):', i)

您还需要排除内容本身中的“cd”(在这种模式中,空格用作分隔符,但可以想象字符串上的变体,如
'ab123:random text1 de23:acdc cd4576:text2'

您可以使用
re.findall(r'\bab\d+:(.*?(::::\s*\bcd |$),i)

它进行了以下修改:
re.findall(r'\bab\d+:((.|\n)*?)(?:\s*\bcd\d+|$)
谢谢。