python - 提取带有可选结束模式的字符串

标签 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\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/

相关文章:

python - 在 Raspberry Pi 上保存图像流的最快方法

python - 更新 INI 文件而不删除注释

java.util.regex.PatternSyntaxException : Illegal repetition near index 12

python-3.x - Pandas - 使用 to_hdf 添加同名数据框使文件大小翻倍

python - sys.exc_info 还是 sys.last_*?

python - 从下标符号构建切片对象

python - 在python中将字符串写入文件

python - 使用 Python 3 在 X 服务器(Raspberry Pi)上显示全屏 jpeg

java - 正则表达式模式匹配 n 个前导空格后跟一个短语

用于http头解析的C正则表达式库