Oracle db regexp 过滤掉不在特定模式中的行
Oracle db regexp to filter out rows that are not in a specific pattern
在 Oracle 数据库 table 中,其中一列具有以下 VARCHAR2
格式:
yyyy-mm-dd hh:mm:ss
我很乐意过滤掉所有与此模式不匹配的行。因此,我在查询中写了以下 regexp
,但查询返回 table 中的所有行,包括匹配 2014-09-10 10:02:33
模式的所有行。
SELECT COLUMN
FROM TABLE
WHERE regexp_like(COLUMN, '^[[:digit:]{4},-,[:digit:]{2},-,[:digit:]{2}, ,[:digit:]{2},:,[:digit:]{2},:,[:digit:]{2}]');
我的查询有什么问题?
你可以试试这个。
select col
from tablename
where regexp_like(col,'^([1-9]\d{3})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$')
[1-9]\d{3}
- 匹配从 1000 到 9999 的所有年份
0[1-9]|1[0-2]
- 匹配从 01 到 12 的月份
0[1-9]|[1-2][0-9]|3[0-1]
- 匹配从 01 到 31 的天数
\s
- 匹配 space
0[0-9]|1[0-9]|2[0-3]
- 匹配从 00 到 23 的小时
[0-5][0-9]
- 匹配从 00 到 59 的分钟,从 00 到 59 的秒
该查询还会为您提供 02-30-2016
等作为有效日期。您需要包含额外的逻辑来匹配具有 30 天的月份和基于闰年的二月。
不建议将date
存储为varchar
。当您使用 to_date
.
转换它时,您可以编写一个 return 只有有效日期的过程
编辑:下面的查询将匹配闰年中除 2 月 29 日以外的所有有效日期。
select col
from tablename
where regexp_like(col,'^([1-9]\d{3})-((0[13578]|10|12)-([0-9]|[1-2][0-9]|3[0-1])|(0[469]|11)-(0[1-9]|[1-2][0-9]|30)|(02-(0[1-9]|[1-2][0-8])))\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$')
在 Oracle 数据库 table 中,其中一列具有以下 VARCHAR2
格式:
yyyy-mm-dd hh:mm:ss
我很乐意过滤掉所有与此模式不匹配的行。因此,我在查询中写了以下 regexp
,但查询返回 table 中的所有行,包括匹配 2014-09-10 10:02:33
模式的所有行。
SELECT COLUMN
FROM TABLE
WHERE regexp_like(COLUMN, '^[[:digit:]{4},-,[:digit:]{2},-,[:digit:]{2}, ,[:digit:]{2},:,[:digit:]{2},:,[:digit:]{2}]');
我的查询有什么问题?
你可以试试这个。
select col
from tablename
where regexp_like(col,'^([1-9]\d{3})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$')
[1-9]\d{3}
- 匹配从 1000 到 9999 的所有年份0[1-9]|1[0-2]
- 匹配从 01 到 12 的月份0[1-9]|[1-2][0-9]|3[0-1]
- 匹配从 01 到 31 的天数\s
- 匹配 space0[0-9]|1[0-9]|2[0-3]
- 匹配从 00 到 23 的小时[0-5][0-9]
- 匹配从 00 到 59 的分钟,从 00 到 59 的秒
该查询还会为您提供 02-30-2016
等作为有效日期。您需要包含额外的逻辑来匹配具有 30 天的月份和基于闰年的二月。
不建议将date
存储为varchar
。当您使用 to_date
.
编辑:下面的查询将匹配闰年中除 2 月 29 日以外的所有有效日期。
select col
from tablename
where regexp_like(col,'^([1-9]\d{3})-((0[13578]|10|12)-([0-9]|[1-2][0-9]|3[0-1])|(0[469]|11)-(0[1-9]|[1-2][0-9]|30)|(02-(0[1-9]|[1-2][0-8])))\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$')