Postgres日期验证正则表达式 [英] postgres date validation regex

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

问题描述

我在postgres中有一张大表,其中大多数日期都采用DD-Mon-YY格式,但是有些行不遵循这种模式,因此可以视为垃圾值。
当我尝试在此列上运行任何date函数时,查询失败,并显示错误消息,表明该垃圾值不是有效的日期格式。

I have a large table in postgres in which most of the dates are in DD-Mon-YY format but some rows do not follow this pattern and can be regarded as junk values. When I try to run any date function on this column, the query fails with the error message that this junk value is not a valid date format.

我的目的是通过编写case语句来跳过包含垃圾值的行。我只想处理那些遵循有效日期格式的行,即 DD-Mon-YY。

My intent is to skip the rows containing junk values by writing a case statement. I will like to process only those rows which follow the valid date format i.e. 'DD-Mon-YY'.

我为日期编写了以下正则表达式模式当我在在线正则表达式测试器上对其进行测试但在postgres上不起作用时。我是Postgres的新手,所以请让我知道我在这里缺少什么。

I have written following regex pattern for date, which is working when I test it on online regex tester but is not working on postgres. I'm new to postgres so please let me know what I'm missing here.

以下代码段在期望返回True时返回False

The following snippet returns False when I'm expecting it to return True

SELECT '23-Dec-83' ~ '^\d{2}-[a-zA-Z]{3}-\d{2}$'


推荐答案

您的正则表达式返回true,但它不好。

Your regex is returning true but it is not good.


  1. 您应尽量避免将日期存储为字符串/ varchar。这会导致几个问题。

  2. 尝试使用正确的数据类型。

不过,处理您的案件的更好的正则表达式可能是:

However a better regex to deal with your case could be:

SELECT '30-Dec-83' ~ '^(([0-2][0-9])|([3][0-1]))-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2}$'

电影演示

FIDDLE DEMO

即使对于

SELECT '23-Mon-83' ~ '^\d{2}-[a-zA-Z]{3}-\d{2}$'  //return True
SELECT '23-Abc-83' ~ '^\d{2}-[a-zA-Z]{3}-\d{2}$'  //return True
SELECT '23-Pqr-83' ~ '^\d{2}-[a-zA-Z]{3}-\d{2}$'  //return True

这是错误的。

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

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