预期的句子类型:
我将在今天晚些时候 4:15
到达
我将在今天晚些时候 14:06
到达。
有几点需要注意:
1- 小时格式为 24h
2- 小时可以是一个字母或 2,而分钟始终是 2。
3- 时间总是在句子中间。
我尝试过的:
import re
response = re.sub(r'^(([01]\d|2[0-3]):([0-5]\d)|24:00)$',
'7:15', 'I will be there at `4:15` later today')
我也试过这个正则表达式 ^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$
而且它也没有用。
最佳答案
这里有几个问题,但这有效:
import re
response = re.sub(r'(?:[01]?\d|2[0-3]):(?:[0-5]\d)|24:00', '7:15', 'I will be there at `4:15` later today')
print(response)
这产生
I will be there at `7:15` later today
您需要去掉 anchor 并使用 ?
使 [01]
可选。最后,将括号更改为非捕获并删除不必要的括号。
关于python - 为什么我的时间替换正则表达式不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48092985/