21.정규 표현식
정규표현식
-
regular expression
-
특정한 패턴과 일치하는 문자열를 ‘검색’, ‘치환’, ‘제거’ 하는 기능을 지원
-
정규표현식의 도움없이 패턴을 찾는 작업(Rule 기반)은 불완전 하거나, 작업의 cost가 높음
-
e.g) 이메일 형식 판별, 전화번호 형식 판별, 숫자로만 이루어진 문자열 등
import re
s = 'My id is kim12341'
a = re.findall('a', s)
print(a)
a = re.findall('kim', s)
print(a)
a = re.findall('m', s)
print(a)
[]
['kim']
['m']
s = 'My id is kim12341'
a = re.findall('[a-z]', s)
print(a)
a = re.findall('[a-z]+', s) # + 연속되 단어
print(a)
a = re.findall('[A-Z]', s) # 알파벳 중에 대문자만 리턴
print(a)
a = re.findall('[0-9]', s) # 숫자만
print(a)
a = re.findall('[0-9]+', s)
print(a)
['y', 'i', 'd', 'i', 's', 'k', 'i', 'm']
['y', 'id', 'is', 'kim']
['M']
['1', '2', '3', '4', '1']
['12341']
s = 'My id is kim12341$%!_#'
a = re.findall('[a-zA-Z0-9]', s) # 소문자, 대문자, 숫자
print(a)
a = re.findall('[a-zA-Z0-9]+', s)
print(a)
a = re.findall('[^a-zA-Z0-9]', s) # [^] not
print(a)
a = re.findall('[\w]', s) # w(소문자) : 소문자, 대문자, _, 숫자
print(a)
a = re.findall('[\w]+', s)
print(a)
a = re.findall('[\W]+', s) # 소문자 w의 반대
print(a)
['M', 'y', 'i', 'd', 'i', 's', 'k', 'i', 'm', '1', '2', '3', '4', '1']
['My', 'id', 'is', 'kim12341']
[' ', ' ', ' ', '$', '%', '!', '_', '#']
['M', 'y', 'i', 'd', 'i', 's', 'k', 'i', 'm', '1', '2', '3', '4', '1', '_']
['My', 'id', 'is', 'kim12341', '_']
[' ', ' ', ' ', '$%!', '#']
def pwd_check(pwd):
if len(pwd)<7 or len(pwd)>12:
print(pwd, '의 길이가 적당하지 않습니다.')
return
if re.findall('[a-zA-Z0-9]+', pwd)[0] != pwd:
print(pwd, '=> 숫자와 영문자로만 구성되어야 합니다.')
return
if len(re.findall('[a-z]',pwd))==0 or len(re.findall('[A-Z]',pwd))==0:
print(pwd, '=> 대문자, 소문자 모두 필요합니다.')
return
print(pwd, '=> 올바른 비밀번호 입니다.')
pwd_check('12test')
pwd_check('123test')
pwd_check('123test%')
pwd_check('123Test')
12test 의 길이가 적당하지 않습니다.
123test => 대문자, 소문자 모두 필요합니다.
123test% => 숫자와 영문자로만 구성되어야 합니다.
123Test => 올바른 비밀번호 입니다.
def email_check(email):
exp = re.findall('^[a-z0-9]{2,}@[a-z0-9]{2,}\.[a-z]{2,}$', email)
if len(exp) == 0:
print(email, '=> 잘못된 형식입니다.')
return False
print(email, '=> 올바른 형식입니다.')
return True
email_check('test@naver')
email_check('test&naver')
email_check('test')
email_check('test@gmail.com')
test@naver => 잘못된 형식입니다.
test&naver => 잘못된 형식입니다.
test => 잘못된 형식입니다.
test@gmail.com => 올바른 형식입니다.
True
email = input('이메일 주소 입력하세요 > ')
if email_check(email):
print('올바른 이메일 형식입니다.')
else:
print('올바른 이메일 형식이 아닙니다.')
이메일 주소 입력하세요 > test
test => 잘못된 형식입니다.
올바른 이메일 형식이 아닙니다.
댓글남기기