我想提取可能出现在两个子字符串之间或原始字符串末尾的子字符串。起始分隔符是 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)
匹配。但是当我尝试添加结束模式时,我找不到所需的答案:
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(r'\bab\d+:(.*?)(?:\s*\bcd|$)', i)
代替。
关于python - 提取带有可选结束模式的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52702788/