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

Python中搜索多个子串匹配时如何获取匹配子串的索引位置

解决方法

你可以直接遍历月份列表找到匹配项后获取对应索引,替换原有逻辑即可,示例代码如下:

matches = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
month_start = -1

for month in matches:
    current_idx = last_chars.find(month)
    if current_idx != -1:
        month_start = current_idx
        break

if month_start != -1:
    # 直接切片到月份出现的位置,丢弃后面所有日期内容
    answer = answer[:month_start]
    print("Removing the Date")

因为你已经确认字符串中仅存在一个匹配的月份,遍历找到第一个匹配项就可以终止循环,拿到的索引就是日期段的起始位置,直接切到这个位置就不用考虑日期长度不一致的问题。

如果想要更严谨避免误匹配,也可以用正则直接匹配末尾的完整日期格式:

import re

# 匹配 月份 1-2位天数, 4位年份 且锚定字符串末尾
date_reg = re.compile(r'(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2}, \d{4}$')
date_match = date_reg.search(last_chars)

if date_match:
    answer = answer[:date_match.start()]
    print("Removing the Date")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:45:04