日期时间格式的动态正则表达式 [英] Dynamic regex for date-time formats

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

问题描述

是否存在现有解决方案,可以根据给定的日期时间格式模式动态创建正则表达式?支持的日期时间格式模式无关紧要(Joda DateTimeFormat java.text.SimpleDateTimeFormat 或其他)。 / p>

作为一个具体示例,对于给定的日期时间格式,例如 dd / MM / yyyy hh:mm ,它应生成相应的正则表达式,以匹配指定格式内的日期时间。

解决方案

我想您的时间格式可以使用有限的字母被构造。也就是说, HH 在24小时制上始终是小时, dd 始终是



由于时间格式的顺序性质,您可以尝试标记的格式字符串dd / mm / yyyy HH:nn 放入数组 [ dd, /, mm, /, yyyy,, HH,:, nn] 。然后,通过将 HH 替换为([[01] [0-9] | 2 [0 -3]) 等。将这些模式原子预先构建到查找表/数组中。数组中所有不在查找表中的部分都是文字。根据正则表达式规则将其转义,并将其附加到模式字符串中。






编辑:作为基于正则表达式的副作用解决方案,当您将查找表的所有正则表达式原子放入括号中并以给定的格式字符串跟踪它们的顺序时,您将能够使用子匹配项从匹配项中提取所需的组件并将其输入到CreateDate函数,因此完全跳过了ParseDate部分。


Is there an existing solution to create a regular expressions dynamically out of a given date-time format pattern? The supported date-time format pattern does not matter (Joda DateTimeFormat, java.text.SimpleDateTimeFormat or others).

As a specific example, for a given date-time format like dd/MM/yyyy hh:mm, it should generate the corresponding regular expression to match the date-times within the specified formats.

解决方案

I guess you have a limited alphabet that your time formats can be constructed of. That means, "HH" would always be "hours" on the 24-hour clock, "dd" always the day with leading zero, and so on.

Because of the sequential nature of a time format, you could try to tokenize a format string of "dd/mm/yyyy HH:nn" into an array ["dd", "/", "mm", "/", "yyyy", " ", "HH", ":", "nn"]. Then go ahead and form a pattern string from that array by replacing "HH" with "([01][0-9]|2[0-3])" and so on. Preconstruct these pattern atoms into a lookup table/array. All parts of your array that are not in the lookup table are literals. Escape them to according regex rules and append them to you pattern string.


EDIT: As a side effect for a regex based solution, when you put all regex "atoms" of your lookup table into parens and keep track of their order in a given format string, you would be able to use sub-matches to extract the required components from a match and feed them into a CreateDate function, thus skipping the ParseDate part altogether.

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

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