본문 바로가기
DB/SQLPLUS

[ORACLE] 정규 표현식

by KhyeonS 2022. 6. 17.

이번엔 정규표현식을 만들어 볼 것 이다.


 정규 표현식(Regular Expression)
 

정규 표현식은 숫자, 문자, 기호 등을 주어진 패턴으로 찾아내서 적용시키는 기법이다.

대부분 C, C++, ShellScripts, Python, JAva, ...등의 프로그래밍 언어와 데이터베이스의 PL/SQL에서 사용된다. 
 ^(~로 시작), $(~로 끝남), [a-z](a~z 중 하나), [a..f](a로 시작되고 f로 끝나는 총 4자리 문자), ^[a-f](a~f로 시작되지 않음), [^PS](P나 S로 시작), ...와 같은 패턴이 있다.

 

  • REGEXP_LIKE(검색_값, 패턴, .. 매치_옵션) 구문은 검색_값은 검색할 문자열, 패턴은 검색할 특정 문자, 매치_옵션은 찾고자 하는 문자이다. 대소문자 구분이 없다면 i를 사용해주면 된다. 

 

  • REGEXP_SUBSTR(검색_값, 패턴1, 패턴2, 위치, 특정_문자, 매치_옵션)은 문자열에서 일부를 추출해준다. 위치는 디폴트로 1이므로 처음부터 찾는다. 특정_문자는 찾고자 하는 특정문자이다. 

 

  • REGEXP_REPLACE(검색_값, 패턴, 대체_값, 위치, 발생, 매치_옵션) 구문은 특정 패턴과 매치되는 부분을 바꿔준다. 

●예제

REGEXP_LIKE(검색_값, 패턴, ... 매치_옵션) 구문은 검색 값은 검색할 문자열, 패턴은 검색할 특정 문자, 매치 옵션은 찹고자 하는 문자이다. 대소문자 구분이 없다면 i 을 사용해주면 된다


제품의 이름중에서 SS로 시작되면서P를 포함하지 않는 제품을 찾아보이시오.
select product_name from product_information
where REGEXP_LIKE(product_name, 'SS[^P]');

select product_name from product_information
where REGEXP_LIKE(product_name, 'SS[^P]');



제품의 이름중에서 SS로 시작되면서 P나 S로 이어지는 제품을 찾아보이시오.
select product_name from product_information
where REGEXP_LIKE(product_name, 'SS[PS]');

select product_name from product_information
where REGEXP_LIKE(product_name, 'SS[PS]');



customers 테이블에서 cust_first_name이 A나 a로 시작되지 않는 고객을 정규표현식으로 보이시오.
select cust_first_name from customers
where REGEXP_LIKE(cust_first_name, '^[A-a]');

select cust_first_name from customers
where REGEXP_LIKE(cust_first_name, '^[A-a]');



REGEXP_SUBSTR
이메일중 앞부분만 추출하겠다.
select cust_email, REGEXP_SUBSTR(cust_email,  '[^@]+') "CUST_ID"
from customers
where nls_territory =  'ITALY'
and rownum <= 5; <=이메일에서 앞에서 부터 @ 전까지
+ : @를 기준으로 골뱅이 앞에서 
+ : 는 까지 라는 의미!!!

select cust_email, REGEXP_SUBSTR(cust_email,  '[^@]+') "CUST_ID"
from customers
where nls_territory =  'ITALY'
and rownum <= 5;



REGEXP_REPLACE
select REGEXP_REPLACE('Oracle is the data    information company',  '( ){2,}',' ') from dual;

select REGEXP_REPLACE('Oracle is the data    information company',  '( ){2,}',' ') from dual;



/*숫자number//(십진수) [[:digit:]] , 소문자 [[:alpha:]], 
소문자와 숫자 [[:alnum:]]
[[: ~:]]를 클래스라고 한다.
\.은 .이 부호라는 의미<= \n, \t, \(, \),.....//

*/650.507.9833 => 65)507-9833 변경/*
select phone_number, 
REGEXP_REPLACE(phone_number,  '([[:digit:]]{3})\.([[:digit:]]{3})\.([[:digit:]]{4})',  
'\1) \2-\3') "NEW_PHONE_NUM" from employees;

select phone_number, 
REGEXP_REPLACE(phone_number,  '([[:digit:]]{3})\.([[:digit:]]{3})\.([[:digit:]]{4})',  
'\1) \2-\3') "NEW_PHONE_NUM" from employees;

'DB > SQLPLUS' 카테고리의 다른 글

[ORACLE]제약 조건  (0) 2022.06.17
[ORACLE] 테이블  (0) 2022.06.17
[ORACLE] 분석함수  (0) 2022.06.16
[ORACLE] DECODE,NVL 기타함수  (0) 2022.06.15
[ORACLE]변환 함수  (0) 2022.06.14

댓글