본문 바로가기

컴퓨터과학/Algorithm

[SQL] [Codewars] 7Kyu - SQL: Regex Replace

 

 

Codewars: Achieve mastery through coding challenge

Codewars is a coding practice site for all programmers where you can learn various programming languages. Join the community and improve your skills in many languages!

www.codewars.com

문제

You are given a table named repositories, format as below:

 

** repositories table schema **

  • project
  • commits
  • contributors
  • address

The table shows project names of major cryptocurrencies, their numbers of commits and contributors and also a random donation address ( not linked in any way :) ).

Your job is to remove all numbers in the address column and replace with '!', then return a table in the following format:

 

** output table schema **

  • project
  • commits
  • contributors
  • address

Case should be maintained.

 

코드

SELECT
  project,
  commits,
  contributors,
  REGEXP_REPLACE(address, '[[:digit:]]', '!', 'g') as address
FROM repositories;

 

설명

아래는 postgresqltutorial에서 제공한 REGEXP_REPLACE의 예시이다. 1)

ABC12345xyz

SELECT REGEXP_REPLACE('ABC12345xyz','[[:alpha:]]','','g');

'12345'

REGEXP_REPLACE에서 'g'는 첫 번째 글자뿐만 아니라 모든 알파벳을 지우라고 함수에게 지시한 것이다.

 

REGEXP_REPLACE의 옵션은 같은 의미라도 다양한 방법으로 줄 수 있다. 아래는 모두 같은 뜻이다.

REGEXP_REPLACE(address, '[[:digit:]]', '!', 'g')
REGEXP_REPLACE(address, '[0-9]', '!', 'g')
REGEXP_REPLACE(address, '\d', '!', 'g')

1) 출처 : https://www.postgresqltutorial.com/regexp_replace/