【问题标题】:Is there a function to check if the given string pattern in valid是否有一个函数来检查给定的字符串模式是否有效
【发布时间】:2021-04-22 11:31:08
【问题描述】:

我需要一个 Oracle 函数来检查给定的输入字符串是否有效。

例如。输入字符串为50-100,145,153

函数应该检查

  1. num1 num2 在 num1-num2
  2. 字符串模式应始终为num1-num2,num3,num4

谢谢

【问题讨论】:

    标签: sql oracle sql-function


    【解决方案1】:

    没有内置函数,但您可以使用正则表达式。例如(只有第一行有效):

    SQL> with test (col) as
      2    (select '50-100,145,153' from dual union all
      3     select '50-49,145,153'  from dual union all
      4     select 'a-2,b,200'      from dual union all
      5     select '10-20,30'       from dual union all
      6     select '1,2-3,4'        from dual
      7    )
      8  select col
      9  from test
     10  where regexp_like(col, '^\d+-\d+,\d+,\d+$')
     11    and to_number(regexp_substr(col, '\w+', 1, 1)) < to_number(regexp_substr(col, '\w+', 1, 2));
    
    COL
    --------------
    50-100,145,153
    
    SQL>
    

    【讨论】:

      【解决方案2】:

      我会使用这种方法:

      with test (col) as
        (select '50-100,145,153' from dual union all  -- ok
         select '50-49,145,153'  from dual union all
         select 'a-2,b,200'      from dual union all
         select '10-20,30'       from dual union all  -- ok
         select '1,2-3,4'        from dual union all  -- ok
         -- additional test values:
         select '1,2,3,7-8,100,120-130,200'  from dual union all -- ok
         select '1-3,7-8,120-130,200'        from dual union all -- ok
         select '1,2,3,8-7,100,120-130,200'  from dual union all -- nope
         select '1,2,3,7-8,100,130-120,200'  from dual union all -- nope
         select '1,2,3,7-8,100,,,120-z,200'  from dual union all -- nope
         select '1,2,3,7-8,100,,,120,200'    from dual           -- nope
        )
      select col
      from test
      where regexp_like(col, '^(((\d+-\d+)|\d+),?)+$')
        and (select 
                count(*)
             from dual
               where to_number(regexp_substr(col,'(\d+)-(\d+)',1,level,null,1))
                   > to_number(regexp_substr(col,'(\d+)-(\d+)',1,level,null,2))
             connect by level<=regexp_count(col,'(\d+)-(\d+)')
            ) = 0;
      
      1. regexp_like(col, '^(((\d+-\d+)|\d+),?)+$') 检查 col 是否仅包含 2 个模式:\d+-\d+\d+,它们之间用逗号分隔。

      2. 在子查询中我们检查是否有num1&gt;num2

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-21
        • 2020-03-03
        • 1970-01-01
        • 2013-02-13
        • 2017-09-22
        • 2020-03-25
        • 2019-05-05
        相关资源
        最近更新 更多