【问题标题】:Reg Exp replace to match hh:mm format in oracle正则表达式替换以匹配 oracle 中的 hh:mm 格式
【发布时间】:2023-03-18 12:19:02
【问题描述】:

使用正则表达式替换编写一个 oracle 查询来修复空间并返回 hh:mm 格式。

with
  test_data (srt_tm) as (
    select '1:00'  from dual union all
    select '01:00' from dual union all
    select ' 01:00' from dual union all
    select '4:00'  from dual union all
    select '04:00' from dual union all
    select ' 04:00' from dual
  )

预期输出:

已尝试查询:

select (strt_tm,regexp_replace(strt_tm,'^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$','hh:mm') as "REPLACE" 
from test_data

【问题讨论】:

  • 去掉多余的括号。
  • 您还没有说出您的查询有什么问题。但是首先你有一个额外的(,它会抛出 ORA-00907;并且您的列名strt_tm 与 CTE 定义不匹配。那是在你了解你的正则表达式实际在做什么之前......
  • 你肯定不是指mm(代表月份),而是mi(代表分钟)?无论如何,这与问题无关;当然,在 replace 中,您不想用输出中的字符串 'hh:mi''hh:mm' 替换输入中的任何内容。此外,还有两个更高级别的问题:(1)为什么“使用正则表达式”是问题的一部分(如果有的话,应该是解决方案的一部分,而不是问题本身),以及(2)你为什么需要更改您的用户名以再次发布问题?你以前的用户名怎么了?
  • 为什么是正则表达式? lpad(trim(srt_tm), 5, '0')如果你必须验证时间,那么使用像validate_conversion这样的内置函数,而不是需要有人支持的自行开发的解决方案
  • 如果您出于某种原因必须使用正则表达式(因为它是一项任务、某个权威的愿望或任何其他外部情况),那么这个问题与 Oracle 无关(或任何其他工具),但需要分解:1)替换部件的可能模式是什么? 2)到目前为止你有什么正则表达式,你觉得它有什么问题? 3) 为什么结果不对?

标签: regex oracle time replace format


【解决方案1】:

只需将额外的 0 添加到小时并删除除最后 2 位之外的所有数字:

select 
  strt_tm,
  regexp_replace(
     regexp_replace(
        strt_tm
       ,'(\d+):'
       ,'0\1:'
     )
   ,'.*(\d{2}:)'
   ,'\1'
  ) as "REPLACE" 
from test_data;

带有 test_data 的完整示例:

with
  test_data (strt_tm) as (
    select '1:00'  from dual union all
    select '01:00' from dual union all
    select ' 01:00' from dual union all
    select '4:00'  from dual union all
    select '04:00' from dual union all
    select ' 04:00' from dual
  )
select 
  strt_tm,
  regexp_replace(
     regexp_replace(
        strt_tm
       ,'(\d+):'
       ,'0\1:'
     )
   ,'.*(\d{2}:)'
   ,'\1'
  ) as "REPLACE" 
from test_data

【讨论】:

  • 选择 strt_tm, regexp_replace( regexp_replace( strt_tm ,'(\d+):' ,'0\1:' ) ,'.*(\d{2}:)' ,'\1' ) 作为 test_data 中的“REPLACE”,其中 strt_tm='1:00' - 这仅返回 1:00 而不是替换列中的 01:00
  • @Sona 没什么:dbfiddle.uk/…
【解决方案2】:

您的测试数据不需要任何正则表达式;只需修剪前导空格,在前面加上一个零,然后取最后 5 个字符:

with test_data (srt_tm) as (
  select '1:00'  from dual union all
  select '01:00' from dual union all
  select ' 01:00' from dual union all
  select '4:00'  from dual union all
  select '04:00' from dual union all
  select ' 04:00' from dual
)
SELECT SUBSTR('0' || LTRIM(srt_tm), -5)
FROM   test_data;

哪些输出:

SRT_TM
01:00
01:00
01:00
04:00
04:00
04:00

db小提琴here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-16
    • 2017-04-05
    • 1970-01-01
    • 2013-12-06
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多