在平常的工作當中,經常需要替換字符串中的字符,比如將身份證號1991年的全部替換為2001年,替換的方式有三種(TRANSLATE、REPLACE、REGEXP_REPLACE),支持嵌套調用:
/*
REPLACE(char,search_string,replacement_string)
'1991' is search_string '2001' is replacement_string REPLACE returns char with every occurrence of search_string replaced with replacement_string.
If replacement_string is omitted or null, then all occurrences of search_string are removed.
If search_string is null, then char is returned. REPLACE的實現是由TRANSLATE函數為基礎,在REPLACE中,原值和被替換項與替換后的項數據類型支持:CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB
*/ SELECT REPLACE('2301231991','1991','2001') FROM DUAL;
執行結果為:'2301232001'
TRANSLATE(char, from_string, to_string)
--' */''' is from_strin --'_' is to_string --被替換項從左至右依次替換,替換項按照使用個數遞減,若替換項不足則替換為'' SELECT TRANSLATE('SQL*Plus User''s Guide', ' */''', '_') FROM DUAL; --執行結果為:SQLPlus_Users_Guide SELECT TRANSLATE('SQL*Plus User''s Guide', ' */''', '__') FROM DUAL; --執行結果為:SQL_Plus_Users_Guide SELECT TRANSLATE('SQL*Plus User''s Guide', ' */''', '___') FROM DUAL; --執行結果為:SQL_Plus_Users_Guide SELECT TRANSLATE('SQL*Plus User''s Guide', ' */''', '____') FROM DUAL; --執行結果為:SQL_Plus_User_s_Guide
REGEXP_REPLACE(source_char,match_parameter
,replace_string)
--REGEXP_REPLACE的實現是由REPLACE函數為基礎,支持正則表達式,可以進行復雜字符處理 SELECT REGEXP_REPLACE('132.546.7890','([[:digit:]]{3})\.([[:digit:]]{3})\.([[:digit:]]{4})','(\1) \2-\3') FROM DUAL ; --The following example examines phone_number, looking for the pattern xxx.xxx.xxxx. Oracle reformats this pattern with (xxx) xxx-xxxx. --執行結果為:(132) 546-7890 SELECT REGEXP_REPLACE('500 Oracle Parkway, Redwood Shores, CA','( ){2,}', ' ') FROM DUAL; --The following example examines the string, looking for two or more spaces. Oracle replaces each occurrence of two or more spaces with a single space. --執行結果為:500 Oracle Parkway, Redwood Shores, CA