본문 바로가기
SWE/Learning Diary

[Python] Regular Expression 정규 표현식 사용 예제

by S나라라2 2022. 9. 27.
반응형

python 정규식 사용 예제

 

no

 

import re

regular expression 모듈 import하기

 

 

  • 숫자만 추출
match = re.findall('[0-9]+', 'rtsp://111.112.113.114:9000/rtspTest')
print(match)
# ['111', '112', '113', '114', '9000']

 

  • 지정한 길이의 숫자만 추출
match = re.findall('[0-9]{4}', 'rtsp://111.112.113.114:9000/rtspTest')
print(match)
# ['9000']

 

  • 특정 문자열 추출
# rtsp 텍스트 찾기
match = re.findall('rtsp', 'rtsp://111.112.113.114:9000/rtspTest')
print(match)
# ['rtsp', 'rtsp']

 

  • 시작 특정 문자열 추출
# 시작이 rtsp 텍스트 찾기
match = re.findall('^rtsp', 'rtsp://111.112.113.114:9000/rtspTest')
print(match)
# ['rtsp']

 

  • URL에서 IP Address, Port 추출하기
m = re.match(r"rtsp://(?P<IP>[0-9.]+):(?P<Port>[0-9]+)/([a-zA-Z])", "rtsp://111.112.113.114:9000/rtspTest")
print(m.groupdict())
# {'IP': '111.112.113.114', 'Port': '9000'}

 

  • 이메일 주소에서 사용자 id, 도메인 추출하기
m = re.match(r"(?P<User>[a-zA-Z0-9]+)@(?P<Domain>[a-zA-Z]+).com", "testID@google.com")
print(m.groupdict())
# {'User': 'testID', 'Domain': 'google'}

 


정규표현식 테스트 사이트 추천

 

https://regex101.com/

 

regex101: build, test, and debug regex

Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java, C#/.NET.

regex101.com

 

반응형