DB/ORACLE

[orcl] replace 와 regxp_replace

배고파요 2022. 4. 14. 13:18
728x90

여기 두개의 데이터가 있고,,

 

4번째에 위치한 " 0 " 만 " - " 문자로 바꾸고 싶다.

 

그냥 replace 를 쓰게 되면, 4번째에 있는 문자 (즉. " 0 " ) 가 모두 " - " 로 바뀌게 된다.

 

왜냐면, 


   REPLACE   

REPLACE( 컬럼명 , "찾을 문자", "바꿀 문자" ) 


즉, 위에서 내가 썼던 건 

--> name 안에 모든 "0" 이란 문자를 "-" 로 바꿔라. 

가 된 것이다.

 

 

 

 

 

 

 

그렇다면,  특정 위치에 있는 문자를  replace  하는 방법은 뭔가?


   REGEXP_REPLACE   

REGEXP_REPLACE( source_char, patteren, replace_string, position, occurrence, math_param ) 

--> REGEXP_REPLACE( 컬럼명, "찾을 문자", "바꿀 문자", 시작 위치, 몇번째로 일치하는 건지, 대소문자 구분 여부 ) 

 

" occurrence (몇번째로 일치하는 건지) " 가 0 이면 일치하는 모든 것. (replace 와 같다고 볼 수 있음.)

" math_param (대소문자 구분 여부) " 는       --> " i " :  대소문자 무시,   -->   " c " : 대소문자 구분


 

 

 

select replace(name, substr(name, 4, 1), '-') as "replace" 
       , 'kk' || regexp_replace(name, '0', '-', 4, 1) as "regxp (정규식)" 
from ha;

 

 

 

 

with strings as(
    select 'aaaAAA 가나다라 111-1111' str from dual union all
    select 'bbbBBB 하파타카 222-2222' str from dual union all
    select 'cccCCC 마바사-아자차 333-3333' str from dual
)
select regexp_replace(str, '[[:alpha:]]', '@') as "알파벳1"
       , regexp_replace(str, '[A-Za-z]', '@') as "알파벳2"
       , regexp_replace(str, '[a-z]', '@') as "알파벳3"
       , regexp_replace(str, '[[:digit:]]', '!') as "숫자"
       , regexp_replace(str, '[0-9]', '◆') as "숫자2"
       , regexp_replace(str, '[가-힝]', '★') as "한글"
from strings;

UTF-8의 경우 --> 가-힟

EUC-KR의 경우 --> 가-힝

 

 

 

출처 : https://jack-of-all-trades.tistory.com/381

728x90