You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从多行字符串中提取最后一次匹配后到对应行行尾的内容

多行字符串提取最后一次匹配指定关键词后到行尾内容的方法

问题说明

处理多行字符串场景下,如果需要提取最后一次出现指定关键词后到该行行尾的内容,不需要保留匹配行之后的其余行,可参考以下解决方案。
原错误用法示例(使用rsplit会带出后续所有行内容):

>>> my_string="hello world \n error: this can be anything \n another line \n error: some failure message here \n any line"
>>> print(my_string.rsplit("error:",1)[1])
 some failure message here 
 any line

解决方案

方法1:rsplit后截断到第一个换行符

在rsplit得到关键词后的内容后,仅取第一个换行符之前的部分即可:

res = my_string.rsplit("error:",1)[1].split('\n',1)[0].strip()
print(res)
# 输出:some failure message here

方法2:逐行遍历记录最后一次匹配结果

遍历所有行,只要匹配到关键词就更新结果,遍历结束后得到的就是最后一次匹配的行内结果,适合复杂匹配规则场景:

target = ""
for line in my_string.splitlines():
    if "error:" in line:
        target = line.split("error:",1)[1].strip()
print(target)
# 输出:some failure message here

方法3:正则表达式一步匹配

用正则的贪婪匹配特性,直接定位最后一次出现关键词的行,提取到行尾的内容:

import re
match_res = re.search(r'[\s\S]*error:\s*(.*)$', my_string, flags=re.M)
if match_res:
    print(match_res.group(1))
# 输出:some failure message here

内容的提问来源于stack exchange,提问作者rodee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 12:54:01