KEEP GOING

[MySQL] 정규 표현식 정리(REGEXP) 본문

code review/sql

[MySQL] 정규 표현식 정리(REGEXP)

jmHan 2022. 2. 9. 14:10
반응형

Regular Expression(정규 표현식) 이란?

- 정규 표현식은 특정한 규칙을 가진 문자열의 집합을 표현하는데 쓰이는 형식 언어

- 문자열을 처리하는 방법 중의 하나

  특정한 조건의 문자를 ‘검색’하거나 ‘치환’할 때 사용 

- mySQL에서는 REGEXP라는 키워드를 사용하여 정규표현식을 처리함

 

 

[기본 형식]

SELECT 컬럼명
FROM 테이블명 WHERE 컬럼명 REGEXP '정규표현식';

 

[기본 문법]

^ : 시작

* : 끝

[abc] : a, b, c 중 하나 

^[abc] : a, b, c 중 하나로 시작하는 문자 

^[abc].* : a, b, c 중 하나로 시작하는 문자열 

[^abc] : a, b, c 전부 아님

 \d : 하나의 숫자 

. : 문자

.* : 문자의 반복 즉 문자열 

[a-z] : a부터 z까지

 

 

 

[사용 예제]

https://www.hackerrank.com/challenges/weather-observation-station-8/problem?isFullScreen=true 

 

Weather Observation Station 8 | HackerRank

Query CITY names that start AND end with vowels.

www.hackerrank.com

[STATION 테이블에서 모음으로 시작하고 모음으로 끝나는 CITY명 조회]

*CITY명은 중복이 없어야 함

[풀이1]

SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '^[aeiou].*' AND CITY REGEXP '.*[aeiou]$'

[풀이2]

SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '^[aeiou].*[aeiou]$'

 

https://www.hackerrank.com/challenges/weather-observation-station-10/problem?isFullScreen=true 

 

Weather Observation Station 10 | HackerRank

Query a list of CITY names not ending in vowels.

www.hackerrank.com

[STATION 테이블에서 모음으로 끝나지 않는 CITY명 조회]

*CITY명은 중복이 없어야 함

[풀이1]

SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '.*[^aeiou]$'

[풀이2]

SELECT DISTINCT CITY
FROM STATION
WHERE CITY NOT REGEXP '.*[aeiou]$'

 

[튜토리얼 사이트 및 실습 사이트]

https://regexone.com/

 

RegexOne - Learn Regular Expressions - Lesson 1: An Introduction, and the ABCs

Regular expressions are extremely useful in extracting information from text such as code, log files, spreadsheets, or even documents. And while there is a lot of theory behind formal languages, the following lessons and examples will explore the more prac

regexone.com

https://regexr.com/

 

RegExr: Learn, Build, & Test RegEx

RegExr is an online tool to learn, build, & test Regular Expressions (RegEx / RegExp).

regexr.com

 

 

반응형

'code review > sql' 카테고리의 다른 글

[MySQL] 1주차  (0) 2022.02.28
[MySQL] LeetCode : Nth highest Salary  (0) 2022.02.18
[MySQL] LeetCode : Consecutive-Numbers  (0) 2022.02.07
[MySQL] LeetCode : Department Top Three Salaries  (0) 2022.02.04
[MySQL] HackerRank : Challenges  (0) 2022.02.02
Comments