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

Python如何裁剪字符串得到保留年月信息的指定格式结果

解决方案

你可以直接用Python的re正则模块实现需求,核心逻辑是匹配到「3位小写月份缩写+4位年份」的组合位置停止,截取前半部分即可,完全适配你给出的所有字符串格式。

完整实现代码

import re

# 待处理的字符串列表
raw_strings = [
    "string1-itd_jan2021-internal",
    "string2itd_mar2021-space",
    "string3itd_feb2021-internal",
    "string4-itd_mar2021-moon",
    "string5itd_jun2021-internal",
    "string6-itd_feb2021-apollo",
]

# 编译正则:匹配从开头到「3个小写字母+4个数字」的部分
pattern = re.compile(r"^(.*[a-z]{3}\d{4})")
processed = [pattern.match(s).group(1) for s in raw_strings]

# 输出结果
for item in processed:
    print(item)

输出结果

string1-itd_jan2021
string2itd_mar2021
string3itd_feb2021
string4-itd_mar2021
string5itd_jun2021
string6-itd_feb2021

逻辑说明

正则^(.*[a-z]{3}\d{4})的规则:

  • ^ 限定匹配从字符串开头开始
  • [a-z]{3}\d{4} 匹配3位小写字母加4位数字的组合,刚好对应你字符串里的jan2021、mar2021这类年月片段
  • .* 匹配年月片段之前的所有字符,外层括号将需要的内容捕获为分组,直接取分组1即可得到目标结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:06:04