scott@[local]:5432:scottdb]
SQL> drop table test;
DROP TABLE
scott@[local]:5432:scottdb]
SQL> create table test(x varchar(32));
CREATE TABLE
scott@[local]:5432:scottdb]
SQL> insert into test values('가나다');
INSERT 0 1
scott@[local]:5432:scottdb]
SQL> insert into test values(100);
INSERT 0 1
scott@[local]:5432:scottdb]
SQL> insert into test values(2);
INSERT 0 1
scott@[local]:5432:scottdb]
SQL> insert into test values('a한글12');
INSERT 0 1
scott@[local]:5432:scottdb]
SQL> insert into test values('999test');
INSERT 0 1
scott@[local]:5432:scottdb]
SQL> insert into test values('a11b22c33');
INSERT 0 1
scott@[local]:5432:scottdb]
SQL> select * from test;
x
-----------
가나다
100
2
a한글12
999test
a11b22c33
(6 rows)
scott@[local]:5432:scottdb]
SQL>
여기서 숫자가 들어가 있는 로우를 추출해볼까요?
이럴때 정규식을 쓰면 아주 편하답니다.
로우중에서 숫자가 하나라도 들어가 있는 로우만 추출해보겠습니다.
scott@[local]:5432:scottdb]
SQL> select * from test where x ~ '[0-9]+'; -- "~" 는 "similar to" 의미입니다.
x
-----------
100
2
a한글12
999test
a11b22c33
(5 rows)
데이터중 숫자가 하나도 들어가 있지 않은 로우만 추출해보겠습니다.
scott@[local]:5432:scottdb]
SQL> select * from test where x !~ '[0-9]+';
x
--------
가나다
(1 row)
scott@[local]:5432:scottdb]
로우 데이터중 숫자부분만 추출해보겠습니다.
scott@[local]:5432:scottdb]
SQL> select x, regexp_matches(x,'[0-9]+') from test; -- 배열을 반환합니다.
x | regexp_matches
-----------+----------------
100 | {100}
2 | {2}
a한글12 | {12}
999test | {999}
a11b22c33 | {11}
(5 rows)
scott@[local]:5432:scottdb]
SQL> select x, (regexp_matches(x,'[0-9]+'))[1] from test;
x | regexp_matches
-----------+----------------
100 | 100
2 | 2
a한글12 | 12
999test | 999
a11b22c33 | 11
(5 rows)
scott@[local]:5432:scottdb]
SQL> select x, regexp_matches(x,'[0-9]+','g') from test; -- 마지막 옵션 g 는 greedy 의 약자입니다.
x | regexp_matches
-----------+----------------
100 | {100}
2 | {2}
a한글12 | {12}
999test | {999}
a11b22c33 | {11}
a11b22c33 | {22}
a11b22c33 | {33}
(7 rows)
SQL> select x, (regexp_matches(x,'[0-9]+','g'))[1] from test;
x | regexp_matches
-----------+----------------
100 | 100
2 | 2
a한글12 | 12
999test | 999
a11b22c33 | 11
a11b22c33 | 22
a11b22c33 | 33
(7 rows)
이제 마지막으로 숫자만으로 이루어진 로우만 필터링해보겠습니다.
scott@[local]:5432:scottdb]
SQL> select x from test where x ~ '^[0-9]+$';
x
-----
100
2
(2 rows)
scott@[local]:5432:scottdb]
SQL>
신기하지 않나요?
여기서는 간단한 소개에 그쳤지만, 정규식의 강력함을 금방 느낄실수 있을겁니다.
정규식을 꼭 공부해보시길 권해드립니다.
정규식만을 따로 다룬 책이 있을정도로 기능이 엄청 방대하답니다.