正则表达式匹配时间 [英] Regex to match time

查看:99
本文介绍了正则表达式匹配时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的用户能够输入时间表单.如果需要更多信息,用户可以用它来表示完成一项任务需要多少时间,如果填满了就会保存在数据库中.

I want my users to be able to enter a time form. If more info necessary, users use this to express how much time is needed to complete a task, and it will be saved in a database if filled.

这是我所拥有的:

/^$|^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/

它匹配空形式或 01:30 和 01:30:00 格式的时间.我真的不需要秒,因为每个任务至少需要一分钟,但我尝试删除它,但它只是崩溃了我的代码并删除了对空字符串的支持..我真的完全不理解正则表达式.

It matches an empty form or 01:30 and 01:30:00 formatted times. I really won't need the seconds as every task takes a minute at least, but I tried removing it and it just crashed my code and removed support for empty string.. I really don't understand regex at all.

我想要的是匹配简单的分钟和简单的小时,例如 3:30、3:00、5.这可能吗?它将极大地改善用户体验并减少浪费输入.但我想保留零可选,以防某些用户觉得输入它很自然.

What I'd like, is for it to also match simple minutes and simple hours, like for instance 3:30, 3:00, 5. Is this possible? It would greatly improve the user experience and limit waste typing. But I'd like to keep the zero optional in case some users find it natural to type it.

推荐答案

我认为以下模式可以满足您的需求:

I think the following pattern does what you want:

p="((([01]?\d)|(2[0-4])):)?([0-5]\d)?(:[0-5]\d)?"

第一部分:

(([01]?\d)|(2[0-3])):)?

是一个可选组,处理格式为 00-24 的小时.

is an optional group which deals with hours in format 00-24.

第二部分:

([0-5]\d)?

是一个可选组,如果表达式中出现小时或秒,则处理分钟.该组还处理仅包含分钟或仅小时的表达式.

is an optional group which deals with minutes if hours or seconds are present in your expression. The group also deals with expressions containing only minutes or only hours.

第三部分:

(:[0-5]\d)?

是处理秒的可选组.

以下示例显示了工作模式:

The following samples show the pattern at work:

In [180]: re.match(p,'14:25:30').string
Out[180]: '14:25:30'

In [182]: re.match(p,'2:34:05').string
Out[182]: '2:34:05'

In [184]: re.match(p,'02:34').string
Out[184]: '02:34'

In [186]: re.match(p,'59:59').string
Out[186]: '59:59'

In [188]: re.match(p,'59').string
Out[188]: '59'

In [189]: re.match(p,'').string
Out[189]: ''

由于每个组都是可选的,因此模式也匹配空字符串.我已经用 Python 对其进行了测试,但我认为它也可以与其他语言一起使用,只需进行最小的更改.

As every group is optional the pattern matches also the empty string. I've tested it with Python but I think it will work with other languages too with minimal changes.

这篇关于正则表达式匹配时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆