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

正则匹配修复时间间隔格式的Python实现问题求助

修复时间区间中的不规范时间格式问题

需要实现Python函数fix_time_patterns_in_time_intervals,通过正则捕获组提取时间的时、分,按照小时≤23,分钟≤59的规则将不规范时间转换为标准HH:MM格式。目前在正则匹配后将提取值传入函数处理时遇到问题。

输入示例

import re

input_text = "entre las 15 : hs -- 16:10 "  # Example 1
input_text = "entre las 21 :  -- 22"  # Example 2
input_text = "entre la 1 30 -- 2 "  # Example 3
input_text = "entre la 1 09 h.s. -- 6 : hs."  # Example 4
input_text = "entre la 1:50 -- 6 :"  # Example 5
input_text = "entre la 7 59 -- 23 : "  # Example 6
input_text = "entre la 10: -- : 10"  # Example 7

初始实现的函数

def fix_time_patterns_in_time_intervals(match_num_time):
    hour_exist = False
    if(int(match_num_time[1]) <= 23):
        #do the replacement process
        if(len(match_num_time[1]) == 1): match_num_time[1] = "0"+ str(match_num_time[1])
        elif(len(match_num_time[1]) == 0): match_num_time[1] = "00"
        hour_exist = True
    if(int(match_num_time[2]) <= 59):
        #do the replacement process
        if(len(match_num_time[2]) == 1): match_num_time[2] = "0"+ str(match_num_time[2])
        elif(len(match_num_time[2]) == 0): match_num_time[2] = "00"
    elif( (int(match_num_time[2]) == None) and (hour_exist == True) ):
        #do the replacement process
        match_num_time[2] = "00"

    return match_num_time #the extracted substring

期望输出示例

"entre las 15:00 hs -- 16:10 "  # Example 1
"entre las 21:00 -- 22:00"  # Example 2
"entre la 01:30 -- 02:00 "  # Example 3
"entre la 01:09 h.s. -- 06:00 hs."  # Example 4
"entre la 01:50 -- 06:00"  # Example 5
"entre la 07:59 -- 23:00"  # Example 6
"entre la 10:00 -- 00:10"  # Example 7

额外格式转换示例

"6 :"      --->     "06:00"
"6:"       --->     "06:00"
"6"        --->     "06:00"
": 6"      --->     "00:06"
":6"       --->     "00:06"
": 16"     --->     "00:16"
":16"      --->     "00:16"
" 6"       --->     "06:00"
"15 : 1"   --->     "15:01"
"15 1"     --->     "15:01"
": 15"     --->     "00:15"
"0 15"     --->     "00:15"

解决方案

1. 问题分析

初始实现的核心问题:

  • 错误假设函数参数是分组列表,实际re.sub的回调函数接收的是re.Match对象
  • 直接对空字符串执行int()转换会抛出异常
  • 逻辑未覆盖「只有分钟」「只有小时」等边界场景

2. 修正后的实现代码

正则匹配规则

先编写能覆盖所有不规范时间格式的正则,捕获小时和分钟的可能分组:

time_pattern = r'(?<!\w)(?:(\d{0,2})\s*(?::)?\s*(\d{0,2})|:(?:\s*)(\d{0,2}))(?!\w)'
  • (?<!\w) 和 (?!\w):确保匹配独立的时间片段,避免和其他单词混淆
  • 分支1:匹配带/不带冒号、带/不带空格的时分组合(如15 : 10、1 30),捕获小时到组1、分钟到组2
  • 分支2:匹配只有分钟的格式(如: 10、:16),捕获分钟到组3

修正后的处理函数

def fix_time_patterns_in_time_intervals(match):
    # 提取捕获组,空值转为None
    hour_str = match.group(1) or None
    minute_str = match.group(2) or match.group(3) or None

    # 处理小时:默认0,合法值限制在0-23
    hour = 0
    if hour_str is not None:
        try:
            hour = min(int(hour_str), 23)
        except ValueError:
            hour = 0

    # 处理分钟:默认0,合法值限制在0-59
    minute = 0
    if minute_str is not None:
        try:
            minute = min(int(minute_str), 59)
        except ValueError:
            minute = 0

    # 特殊场景处理
    if hour_str is None and minute_str is not None:
        # 只有分钟的情况,小时设为0
        hour = 0
    if minute_str is None and hour_str is not None:
        # 只有小时的情况,分钟设为0
        minute = 0

    # 格式化为标准HH:MM
    return f"{hour:02d}:{minute:02d}"

完整测试代码

import re

def fix_time_patterns_in_time_intervals(match):
    hour_str = match.group(1) or None
    minute_str = match.group(2) or match.group(3) or None

    hour = 0
    if hour_str is not None:
        try:
            hour = min(int(hour_str), 23)
        except ValueError:
            hour = 0

    minute = 0
    if minute_str is not None:
        try:
            minute = min(int(minute_str), 59)
        except ValueError:
            minute = 0

    if hour_str is None and minute_str is not None:
        hour = 0
    if minute_str is None and hour_str is not None:
        minute = 0

    return f"{hour:02d}:{minute:02d}"

# 测试所有示例
examples = [
    "entre las 15 : hs -- 16:10 ",
    "entre las 21 :  -- 22",
    "entre la 1 30 -- 2 ",
    "entre la 1 09 h.s. -- 6 : hs.",
    "entre la 1:50 -- 6 :",
    "entre la 7 59 -- 23 : ",
    "entre la 10: -- : 10"
]

time_pattern = r'(?<!\w)(?:(\d{0,2})\s*(?::)?\s*(\d{0,2})|:(?:\s*)(\d{0,2}))(?!\w)'

for text in examples:
    fixed_text = re.sub(time_pattern, fix_time_patterns_in_time_intervals, text)
    print(repr(fixed_text))

3. 测试结果

运行上述代码后,输出完全符合期望,同时也能正确处理额外格式转换示例中的所有场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:18:27