用正则表达式匹配时间字符串 [英] Matching a time string with a regular expression

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

问题描述

我想将字符串中的时间 (10.00) 与日期和时间 ("21.01.08 10.00") 匹配.我正在使用以下正则表达式:

I would like to match the time (10.00) from a string with the date and time ("21.01.08 10.00"). I'm using the following regular expression:

new RegExp("\\b[0-9]{1,2}\\.[0-9]{1,2}\\b" "g");

但这与 21.01.08 和 10.00 的 21.01 相匹配.

But this matches 21.01 from 21.01.08 and 10.00.

我使用 PCRE 作为我的正则表达式引擎.

I'm using PCRE as my regualar expression engine.

更新:

对不起,我应该更清楚.数据和时间是更大字符串的一部分.我想从那个字符串中提取时间.

I'm sorry, i should have more been more clear. The data and time are part of a larger string. I want to extract the time from that string.

例如:

21.01.08 从 10.00 开始,将在图书馆举行派对"21.08.08 - 10:00 将举行派对"08 年 8 月 21 日,您安排了.............将在 10.00 开始"

"On 21.01.08 from 10.00 a party will take place in the library" "21.08.08 - At 10:00 there will be a party" "On 21.08.08 you are scheduled for a ... . The ... will begin at 10.00"

这可能吗?

推荐答案

您原来的正则表达式不起作用,因为 \b(词边界)在."处匹配.在21.01.08"中.您需要更稳健地对边界进行编码:

Your original regex didn't work because \b (word boundary) matches at the "." in "21.01.08." You need to code the boundaries more robustly:

(?:[^\d:.]|^)(\d\d?[.:]\d\d)(?![.:\d])

这会以您使用的任何一种表示法捕获时间,但不包括日期.请注意,它不会验证时间.例如,它会匹配 "88:99" 验证时间是可能的,但会使模式显着复杂化,并且在大多数情况下可能会矫枉过正.

This captures the time, in either of the notations you used, while excluding dates. Note that it does not validate the time. For example, it would match "88:99" Validating the time is possible but complicates the pattern significantly and is likely to be overkill for most situations.

最好使用后视而不是非捕获分组,但 PCRE 不支持可变宽度后视.

It would be nice to use a look-behind instead of the non-capturing grouping but PCRE don't support variable-width look-behind.

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

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