Oracle REGEXP只替换第一个字符

时间:2015-02-10 21:18:29

标签: regex oracle regexp-replace

在下面的例子中:

WITH X(DATA, ORD)
AS
(         
Select '@asdf@'   , 01 FROM DUAL UNION
Select '\qw@er\'  , 02 FROM DUAL UNION
Select '-zxcv-@' , 03  FROM DUAL UNION
Select '_poiu@' ,  04 FROM DUAL 
)

SELECT
REGEXP_REPLACE(DATA, '[@\-_]', '', 1)
FROM X
ORDER BY ORD;  
;  

我收到了这个回复:

asdf 
qwer
-zxcv- 
poiu

但我想替换“@”,或“\”或“ - ”或“_”,只要它是字符串中的第一个字符,而不是中间。 此外,它不适用于“ - ”字符。

2 个答案:

答案 0 :(得分:2)

以下正则表达式应该有效:^[@\\_-]。请注意,短划线-必须是字符类中的最后一个字符。

WITH X AS (
  SELECT '@asdf@' AS data, 01 AS ord FROM DUAL UNION
  SELECT '\qw@er\', 02 FROM DUAL UNION
  SELECT '-zxcv-@', 03  FROM DUAL UNION
  SELECT '_poiu@',  04 FROM DUAL 
)
SELECT REGEXP_REPLACE(DATA, '^[@\\_-]')
 FROM X
ORDER BY ORD

答案 1 :(得分:1)

相反,请使用此

REGEXP_REPLACE(DATA, '^[@|\\|-|_]', '', 1)

注意^字符,它指定字符串的开头。

查询

WITH X(DATA, ORD)
AS
(         
Select '@asdf@'   , 01 FROM DUAL UNION
Select '\qw@er\'  , 02 FROM DUAL UNION
Select '-zxcv-@' , 03  FROM DUAL UNION
Select '_poiu@' ,  04 FROM DUAL 
)
SELECT
REGEXP_REPLACE(DATA, '^[@|\\|-|_]', '', 1)
FROM X
ORDER BY ORD; 

给我结果

  

asdf @,qw @ er,zxcv @,poiu @,