提取具有可选结束模式的字符串



我想提取一个子字符串,该子字符串可能出现在两个子字符串之间或原始字符串的末尾。起始分隔符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('abd+:(.*)', i)匹配。但是当我尝试添加结束模式时,我找不到所需的答案:

re.findall('abd+:(.*)', i)
>>> ['random text1 cd4576: text2'], [' text1'], ['rand text2 cd765: text1']
re.findall('^abd+:(.*)cdd+:', i)
>>>['random text1 '], [], ['rand text2 ']

你可以改用re.findall(r'babd+:(.*?)(?:s*bcd|$)', i)

尝试将 or "|" 与组一起使用,如下所示:

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

您还需要排除内容本身中的"CD"(在此模式中,空格用作分隔符,但想象字符串上的变体,例如'ab123:random text1 de23:acdc cd4576:text2'

最新更新