Oracle regexp忽略重复字符

时间:2013-08-12 06:14:12

标签: sql regex oracle oracle11g

我有一个字符串:

hheelllloo wwoorrlldd !! 应返回hello world!

我的上述尝试是

SELECT regexp_substr('hheelllloo wwoorrlldd !!', '.', LEVEL*2-1)l_val
FROM dual
CONNECT BY LEVEL <= LENGTH('hheelllloo wwoorrlldd !!')/2;

但它不是我需要的方式而且逻辑没有被正确使用。 我也尝试过使用'(\w)\1'

我对样本数据的预期结果:

WITH t AS
     ( SELECT 'hheelllloo wwoorrlldd!!' AS word FROM dual
     UNION
     SELECT 'hellow world!' FROM dual
     UNION
     SELECT 'ootthheerrss' FROM dual
     UNION
     SELECT 'ootthheeerrss' FROM dual
     )
SELECT * FROM t;

输出应该如下:

 hello world!    --expression applied
 hellow world!     -- not needed for non-repeated characters
 others           --expression applied
 otheers          --applied and extra `e` considered as non-repeated.

我可以在一个查询中创建整个。还是第一个? 在此先感谢,这仅适用于我的练习并了解不同的逻辑。

2 个答案:

答案 0 :(得分:3)

您可以使用regexp_replace()正则表达式函数和后向引用:

SQL> WITH t1(col) AS (
  2    select 'hheelllloo wwoorrlldd!!' from dual union all
  3    select 'hellow world!'           from dual union all
  4    select 'ootthheerrss'            from dual union all
  5    select 'ootthheeerrss'           from dual
  6  )
  7  select regexp_replace(col, '(.)\1', '\1') as res
  8    from t1
  9  ;

RES
--------------
hello world!
helow world!
others
otheers

答案 1 :(得分:0)

And
select regexp_replace('A;A;B;B', '(.)\1', '\1')
from `dual`

输出:

A;B ????????

我有这个答案。

相关问题