正则表达式仅在整数时删除小数

时间:2016-10-05 14:21:19

标签: regex oracle replace

我希望取一个百分比并删除小数,%,并在需要时进行舍入。除非它只是一个小数,在这种情况下只删除%。我还有<1%的特例,我可以单独处理。所以我们从[<]|[\.]+[\d]*|%$开始,删除小数和%。但是不圆,并取出.5%。我不知道是什么或如何添加一些东西来解决这个问题。它甚至可能吗?

我需要:

'.5%'   to .5  
'0%'    to  0  
'<1%'   to .1  
'65%'   to 65  
'65.5%' to 66  
'65.4%' to 65  

2 个答案:

答案 0 :(得分:0)

尝试这样的事情。

  • cte是测试用例
      sql demo中的
    • 必须使用,作为小数分隔符。
  • 清理字符串
    • 删除%字符
    • 处理特殊文字&#39;&lt; 1%&#39;
    • 转换为float
  • 最终查询返回带小数的数字,如果< 1但是更大的数字

<强> SQL DEMO

WITH cte(item) as (
    SELECT ',5%' FROM DUAL UNION
    SELECT '0%' FROM DUAL UNION
    SELECT '<1%' FROM DUAL UNION
    SELECT '65%' FROM DUAL UNION
    SELECT '65,5%' FROM DUAL UNION
    SELECT '65,4%' FROM DUAL      
), clean as (
    SELECT item, CASE WHEN item = '<1%' THEN 0.1
                      ELSE CAST(REPLACE(item, '%')  AS float) 
                 END as flt
    FROM cte   
)
SELECT item, 
       flt,    
        CASE WHEN flt = 0 then 0   -- no need this one is also handle for the next case
             WHEN flt < 1 then flt                               
             ELSE ROUND(flt)
        END as final
FROM clean

<强>输出

enter image description here

答案 1 :(得分:0)

这是我对它的看法。使用TRANSLATE()将小于号替换为小数,并同时删除百分号。如果超过1则回合。

SQL> with tbl(data) as (
     select '.5%'   from dual union
     select '0%'    from dual union
     select '<1%'   from dual union
     select '65%'   from dual union
     select '65.5%' from dual union
     select '65.4%' from dual
   )
   select data BEFORE,
          case
            when translate(data, '<%', '.') < 1
              then to_char(cast(translate(data, '<%', '.') as float))
            when translate(data, '<%', '.') > 1
              then to_char(round(cast(replace(data, '%') as float)))
          end  AFTER
   from tbl;

BEFOR AFTER
----- ----------------------------------------
.5%   .5
0%    0
65%   65
65.4% 65
65.5% 66
<1%   .1

6 rows selected.

SQL>