Skip to main content
 首页 » 编程设计

python之用可选模式替换正则表达式

2025年05月04日30zdz8207

我想将时间分隔符从法语方式转换为更标准的方式:

  • “17:30”变为“17:30”
  • “9h”变成“9:00”

使用正则表达式我可以将 17h30 转换为 17:30 但我没有找到将 9h 转换为 9 的优雅方法:00

这是我到目前为止所做的:

import re 
texts = ["17h30", "9h"] 
hour_regex = r"(\d?\d)h(\d\d)?" 
[re.sub(hour_regex, r"\1:\2", txt) for txt in texts] 
>>> ['17:30', '9:'] 

我想做的是“如果\2 没有匹配到任何东西,就写 00”。

PS:当然我可以使用更详细的正则表达式,如“([12]?\d)h[0123456]\d”,以便在匹配时间时更加精确,但这不是这里的重点。

请您参考如下方法:

Effectively re.compile 函数和 or 条件:

import re 
 
texts = ["17h30", "9h"] 
hour_regex = re.compile(r"(\d{1,2})h(\d\d)?") 
res = [hour_regex.sub(lambda m: f'{m.group(1)}:{m.group(2) or "00"}', txt)  
       for txt in texts] 
print(res)   # ['17:30', '9:00']