ORACLE中的字符串替換 replce、regexp_replace 和 translate

1、語法 

replace(str_source,str1,str2)  把 str_source 中 str1 字符串替換爲 str2 字符串,當 str2 爲 null 或'' 時,與下個做用相同 

replace(str_source,str1)         把str_source 中的 str1 字符串剔除 

regexp_replace(str_source,pattern_str,rep_str) 支持正則表達式,用法相似於 replace,但功能更強大 

regexp_replace(str_source,pattern_str)   把 str_source 中的 pattern_str 字符串剔除 

translate(str_source,chr1,chr2) 以字符爲單位,把 str_source 中的 chr1 字符對應替換爲 chr2。若是 chr1 比chr2 長,那麼在 chr1 中而不在 chr2 中的字符將被剔除,由於沒有對應的替換字符。需注意 chr2 不能爲 null 或'',不然返回值也爲空 



2、示例 



(1)select replace('abcc123','abc','123'),replace('abcc123','abc') from dual; 

REPLACE('ABCC123','ABC','123') REPLACE('ABCC123','ABC') 
------------------------------ ------------------------ 
123c123                        c123 





(2)select regexp_replace('abcc123','abc','*'),regexp_replace('abcc123','[ac]','*'),regexp_replace('abcc123','[ac]') from dual; 

REGEXP_REPLACE('ABCC123','ABC' REGEXP_REPLACE('ABCC123','[AC] REGEXP_REPLACE('ABCC123','[AC] 
------------------------------ ------------------------------ ------------------------------ 
*c123                          *b**123                        b123 
一、用字符串'*'替換 'abc'字符串; 

二、用字符串'*'替換 'a'和'c'字符,涉及到正則表達式的用法。 





(3)select translate('abcc123a','abc','-+='),translate('abcc123a','abc','-+'),translate('abcc123a','#abc','#') from dual; 

TRANSLATE('ABCC123A','ABC','-+ TRANSLATE('ABCC123A','ABC','-+ TRANSLATE('ABCC123A','#ABC','# 
------------------------------ ------------------------------ -------------------- 
-+==123-                       -+123-                         123 
一、用字符'-'、'+'、'='對應替換'a','b','c'字符; 

二、'abc'長度爲 3,'-+'長度爲 2,字符'c'沒有對應的字符來替換,所以被剔除掉; 

三、剔除掉字符'a'、'b'、'c',translate 有 # 的特殊用法,以 # 開頭的表示全部字符。正則表達式

來源:http://it158.iteye.com/blog/1153539regexp

相關文章
相關標籤/搜索