Python에서 정규 표현식을 어떻게 작성하나요?

Python으로 코딩 인터뷰 문제 연습하기

Kirill Smirnov

Data Science Consultant, Altran

정의

정규 표현식: 텍스트에서 찾을 패턴을 정의하는 특수 문자(메타문자) 시퀀스.

 

cat

"I have a cat. My cat likes to eat a lot. It also catches mice."

Python으로 코딩 인터뷰 문제 연습하기

정의

정규 표현식: 텍스트에서 찾을 패턴을 정의하는 특수 문자(메타문자) 시퀀스.

 

cat

"I have a cat. My cat likes to eat a lot. It also catches mice."

Python으로 코딩 인터뷰 문제 연습하기

복합 패턴

예시:

[email protected]은 John의 이메일입니다. 그는 자주 상사 [email protected]에게 씁니다. 하지만 메일은 비서 [email protected]에게 전달됩니다.

Python으로 코딩 인터뷰 문제 연습하기

복합 패턴

예시:

**[email protected]은 John의 이메일입니다. 그는 자주 상사 [email protected]에게 씁니다. 하지만 메일은 비서 [email protected]**에게 전달됩니다.

Python으로 코딩 인터뷰 문제 연습하기

특수 문자

단순 문자와 숫자는 자기 자신과 매칭됩니다:

  • a $\rightarrow$ a
  • A $\rightarrow$ A
  • 1 $\rightarrow$ 1

점(dot)은 아무 문자나 매칭:

  • . $\rightarrow$ 임의의 문자

. $\rightarrow$ 'a', '1', '"', ' ', ...

  • \. $\rightarrow$ .
Python으로 코딩 인터뷰 문제 연습하기

특수 문자

다음 메타문자는 \ 뒤에 문자가 오는 형태입니다:

  • \w $\rightarrow$ 영숫자 또는 밑줄(_)

\w $\rightarrow$ '1', 'a','_', ...

  • \d $\rightarrow$ 숫자

\d $\rightarrow$ '1', '2','3', ...

  • \s $\rightarrow$ 공백 문자

\s $\rightarrow$ ' ', '\t', ...

Python으로 코딩 인터뷰 문제 연습하기

대괄호

여러 메타문자는 대괄호로 묶을 수 있습니다:

  • [aAbB] $\rightarrow$ a, A, b, B
  • [a-z] $\rightarrow$ a, b, c, ...
  • [A-Z] $\rightarrow$ A, B, C, ...
  • [0-9] $\rightarrow$ 0, 1, 2, ...
  • [A-Za-z] $\rightarrow$ A, B, C, ..., a, b, c, ...
Python으로 코딩 인터뷰 문제 연습하기

반복 수량자

  • * $\rightarrow$ 없음 또는 무한 반복

a* $\rightarrow$ '', 'a', 'aa', ...

  • + $\rightarrow$ 최소 1회 이상 존재

a+ $\rightarrow$ 'a', 'aa', 'aaa', ...

  • ? $\rightarrow$ 있어도 되고 없어도 됨

a? $\rightarrow$ '', 'a'

  • {n, m} $\rightarrow$ n~m회 존재

a{2, 4} $\rightarrow$ 'aa', 'aaa', 'aaaa'

Python으로 코딩 인터뷰 문제 연습하기

이메일 정규식

예시:

**[email protected]은 John의 이메일입니다. 그는 자주 상사 [email protected]에게 씁니다. 하지만 메일은 비서 [email protected]**에게 전달됩니다.

[\w\.]+@[a-z]+\.[a-z]+

Python으로 코딩 인터뷰 문제 연습하기

이메일 정규식

예시:

**[email protected]은 John의 이메일입니다. 그는 자주 상사 [email protected]에게 씁니다. 하지만 메일은 비서 [email protected]**에게 전달됩니다.

[\w\.]+@[a-z]+\.[a-z]+

 

[\w\.]+ $\rightarrow$ john.smith, boss, info

영문자, 숫자, 밑줄, 점 중 최소 1자

Python으로 코딩 인터뷰 문제 연습하기

이메일 정규식

예시:

**[email protected]은 John의 이메일입니다. 그는 자주 상사 [email protected]에게 씁니다. 하지만 메일은 비서 [email protected]**에게 전달됩니다.

[\w\.]+@[a-z]+\.[a-z]+

 

@ $\rightarrow$ @

Python으로 코딩 인터뷰 문제 연습하기

이메일 정규식

예시:

**[email protected]은 John의 이메일입니다. 그는 자주 상사 [email protected]에게 씁니다. 하지만 메일은 비서 [email protected]**에게 전달됩니다.

[\w\.]+@[a-z]+\.[a-z]+

 

[a-z]+ $\rightarrow$ mailbox, company

소문자 최소 1자

Python으로 코딩 인터뷰 문제 연습하기

이메일 정규식

예시:

**[email protected]은 John의 이메일입니다. 그는 자주 상사 [email protected]에게 씁니다. 하지만 메일은 비서 [email protected]**에게 전달됩니다.

[\w\.]+@[a-z]+\.[a-z]+

 

\. $\rightarrow$ .

Python으로 코딩 인터뷰 문제 연습하기

이메일 정규식

예시:

**[email protected]은 John의 이메일입니다. 그는 자주 상사 [email protected]에게 씁니다. 하지만 메일은 비서 [email protected]**에게 전달됩니다.

[\w\.]+@[a-z]+\.[a-z]+

 

[a-z]+ $\rightarrow$ com

소문자 최소 1자

Python으로 코딩 인터뷰 문제 연습하기

re 패키지

import re

pattern = re.compile(r'[\w\.]+@[a-z]+\.[a-z]+')
text = '[email protected] is the e-mail of '\
'John. He often writes to his boss at '\
'[email protected]. But the messages get forwarded '\
'to his secretary at [email protected].'
Python으로 코딩 인터뷰 문제 연습하기

re.finditer()

result = re.finditer(pattern, text)
print(result)
<callable_iterator object at 0x7f5dff81af98>
for match in result:
    print(match)
<_sre.SRE_Match object; span=(0, 22), match='[email protected]'>
<_sre.SRE_Match object; span=(77, 93), match='[email protected]'>
<_sre.SRE_Match object; span=(146, 162), match='[email protected]'>
Python으로 코딩 인터뷰 문제 연습하기

re.finditer()

result = re.finditer(pattern, text)
print(result)
<callable_iterator object ...>
for match in result:
    print(match.group())
    print(match.start())
    print(match.end())
Python으로 코딩 인터뷰 문제 연습하기

re.findall()

substrings = re.findall(pattern, text)
print(substrings)
['[email protected]', '[email protected]', '[email protected]']
Python으로 코딩 인터뷰 문제 연습하기

re.split()

split_list = re.split(pattern, text)
print(split_list)
['',
 ' is the e-mail of John. He often writes to his boss at ',
 '. But the messages get forwarded to his secretary at ',
 '.']
Python으로 코딩 인터뷰 문제 연습하기

연습해 봅시다!

Python으로 코딩 인터뷰 문제 연습하기

Preparing Video For Download...