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

如何基于前置正则匹配实现字符串的条件替换?

正则条件替换方案:处理时间后的时段短语

需求说明

  • 当带冒号的时间格式(如XX:XX)后接指定时段短语(如de la tarde、en la noche)且无am/pm后缀时,将时段短语替换为pm
  • 当带冒号的时间格式(含XX:XX am/pm或XX:XXam/pm)后接指定时段短语时,直接删除该时段短语
  • 支持动态扩展时段短语列表,适配任意次数的匹配替换场景

实现方案

核心思路

通过正则分组匹配两种目标场景,结合回调函数区分处理逻辑:

  1. 分组1:匹配带冒号的时间(XX:XX)
  2. 分组2:可选匹配am/pm后缀(兼容带空格或无空格的格式)
  3. 分组3:匹配任意指定的时段短语

代码实现

import re

def process_time_phrases(text):
    # 可扩展的时段短语列表,新增短语直接添加即可
    time_phrases = ['de la tarde', 'en la noche', 'por la noche']
    # 构建正则模式:匹配时间 + 可选am/pm + 时段短语
    pattern = re.compile(
        r'(\d{1,2}:\d{2})(\s?[apm]{2})?\s+(' + '|'.join(map(re.escape, time_phrases)) + r')',
        re.IGNORECASE
    )
    
    def replace_match(match):
        time_part = match.group(1)
        ampm_part = match.group(2) or ''
        # 根据是否存在am/pm后缀执行不同替换逻辑
        if ampm_part:
            return f"{time_part}{ampm_part}"
        else:
            return f"{time_part} pm"
    
    return pattern.sub(replace_match, text)

# 测试示例1
input1 = "A las 19:30 de la tarde salimos!! hay que tener cuidado porque a eso de las 19:30pm de la tarde pasan muchos autos, ademas es importante llegar alla antes de las 20 30 hs, ya que a las 21:00 pm cierran alg1s negocios, sin embargo el cine esta abierto hasta las 23:30 pm de la noche"
output1 = process_time_phrases(input1)
print("示例1输出:")
print(output1)

# 测试示例2
input2 = "Tras pasar las horas de la tarde a las 19:30 de la noche salimos de la casa juntos!! es importante llegar alla antes de las 20:30 pm de la noche, ya que a las 21:00 pm de la noche cierran alg1s negocios, sin embargo el cine esta abierto hasta la 21:00 de la noche"
output2 = process_time_phrases(input2)
print("\n示例2输出:")
print(output2)

扩展性说明

  • 新增时段短语:直接在time_phrases列表中添加即可,例如添加'por la tarde',正则会自动包含该短语的匹配
  • 特殊字符兼容:使用re.escape处理短语,避免短语中的特殊字符干扰正则匹配逻辑
  • 大小写兼容:re.IGNORECASE参数确保匹配AM/PM等大小写变体

测试结果

  • 示例1输出与需求完全一致:正确替换19:30 de la tarde为19:30 pm,删除19:30pm de la tarde中的时段短语,保留20 30 hs不变
  • 示例2输出符合预期:替换19:30 de la noche为19:30 pm,删除20:30 pm de la noche中的时段短语,替换21:00 de la noche为21:00 pm

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:15:41