以正则表达式匹配小时/分钟/秒-更好的方法? [英] Matching hours/minutes/seconds in regular expressions - a better way?

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

问题描述

所以我需要从以下条目中减去小时,分钟和秒钟:

So I need to get hours, minutes and seconds out of entries like these:

  • 04:43:12
  • 9.43.12
  • 1:00
  • 01.04
  • 59
  • 09

前两个是小时,分钟和秒. 旁边是分钟和秒. 最后两个只是几秒钟.

The first two is hours, minutes and seconds. Next to is minutes and seconds. Last two is just seconds.

然后我想出了这个正则表达式,它可以工作..:

And I came up with this regexp, that works..:

\A(?<hours>\d{1,2})(?::|\.)(?<minutes>\d{1,2})(?::|\.)(?<seconds>\d{1,2})\z|\A(?<minutes>\d{1,2})(?::|\.)(?<seconds>\d{1,2})\z|\A(?<seconds>\d{1,2})\z

但这很丑陋,我想将其重构为不是3种不同的表达方式(主要是为了学习).我试过了:

But it is ugly, and I want to refactor it down to not be 3 different expressions (mostly just to learn). I tried this:

\A(?:(?<hours>\d{1,2})(?::|\.){0,1})(?:(?<minutes>\d{1,2})(?::|\.){0,1})(?:(?<seconds>\d{1,2}){0,1})\z

但这不起作用-有时会花几分钟和几秒钟来搞砸.我的大脑受伤了,我无法弄清楚我在做什么错.

But that does not work - minutes and seconds sometimes get screwed up. My brain is hurting, and I can't figure out, what I am doing wrong.

推荐答案

我的建议:

(?:(?:(?<hh>\d{1,2})[:.])?(?<mm>\d{1,2})[:.])?(?<ss>\d{1,2})

结构化:

(?:                     # group 1 (non-capturing)
  (?:                   #   group 2 (non-capturing)
    (?<hh>\d{1,2})      #     hours
    [:.]                #     delimiter
  )?                    #   end group 2, make optional
  (?<mm>\d{1,2})        #   minutes
  [:.]                  #   delimiter
)?                      # end group 1, make optional
(?<ss>\d{1,2})          # seconds (required)

如果愿意,可以将正则表达式包装在定界符中-例如单词边界\b或字符串锚点(^$).

If you wish, you can wrap the regex in delimiters - like word boundaries \b or string anchors (^ and $).

考虑一下,您可以进一步限制它以捕获仅有意义的时间.使用

Thinking about it, you can restrict that further to capture times that make sense only. Use

[0-5]?\d

代替

\d{1,2}

仅在适当的位置(秒和分钟)捕获0到59之间的值.

to capture values between 0 and 59 only, where appropriate (seconds and minutes).

这篇关于以正则表达式匹配小时/分钟/秒-更好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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