Jun's Blog
간단한 기능 구현해보기(정규 표현식) - (8) 본문
1. 혼합 데이터에서 원하는 항목들만 추출해보기
주어진 list에서 문자열 2개와 숫자 3개로 구성된 항목들 찾기
import re
from jupyter_core.version import pattern
print('문자열 2개와 숫자 3개로 구성된 항목들 찾기')
mylist = ['ab123','cd456','ef789','abc12']
# regex = '[a-z]{2}[0-9]{3}' # 정규 표현식
regex = '[a-z]{2}\d{3}' # \d 는 숫자 1개를 의미하고 [0-9]와 동일한 의미
pattern = re.compile(regex) # 정규식 패턴
for item in mylist:
if pattern.match(item):
print(f'문자열 {item}은 조건에 적합합니다.')
else :
print(f'문자열 {item}은 조건에 부적합합니다.')
# end if
# end for
<실행결과>
주어진 list에서 문자열 "a"와 ".txt" 사이에 숫자가 최소 3개 이상인 항목들 구하기
print('문자열 "a"와 ".txt" 사이에 숫자가 최소 3개 이상인 항목들 구하기')
mylist02 = ['a1.txt', 'a12.txt', 'a123.txt','a1234.txt']
regex = 'a[0-9]{3,}.txt'
pattern = re.compile(regex)
for item in mylist02:
if pattern.match(item):
print(f'문자열 {item}은 조건에 적합합니다.')
else :
print(f'문자열 {item}은 조건에 부적합합니다.')
# end if
# end for
<실행결과>
주어진 list에서 문자열 "c"와 "t" 사이에 "a"가 1번 이상인 항목들 구하기
print('문자열 "c"와 "t" 사이에 "a"가 1번 이상인 항목들 구하기')
mylist03 = ['at', 'cat', 'caat', 'caaat']
regex = 'ca+t'
pattern = re.compile(regex)
for item in mylist03:
if pattern.match(item):
print(f'문자열 {item}은 조건에 적합합니다.')
else :
print(f'문자열 {item}은 조건에 부적합합니다.')
# end if
# end for
<실행결과>
주어진 list에서 정규 표현식을 활용하여 특정 부분만 출력해 보기
strip() : Python 문자열 메서드 중 하나로, 문자열의 양쪽 끝에서 특정 문자를 제거하는 역할
ex) rstrip('A'), lstrip('.'), strip()
import re
addressList = [
"('강원원주시웅비1길3');",
"('강원도철원군서면화수로124번길2-15');",
"('강원도평창군봉평면태기로54');",
"('강원강릉시강변로501번길23';)"
]
regex = "\d\S*\'"
pattern = re.compile(regex)
for address in addressList:
mymatch = pattern.search(address)
print(mymatch.group().rstrip("\'"))
# end for
<실행결과>
특정 파일에서 ID 정보만 추출해보세요. ID정보는 "("와 ")" 사이에 있는 문자라고 가정합니다.
import re
myfile = open(file='myid.txt', mode='rt', encoding='UTF-8')
mylist = [item.strip() for item in myfile.readlines()]
print(mylist)
myfile.close()
for item in mylist:
regex = '\(\S+\)'
pattern = re.compile(regex)
popdata = pattern.search(item)
if(popdata != None):
result = str(popdata.group().replace('(', '').replace(')', ''))
print(result)
# end for
<실행결과>
'Python' 카테고리의 다른 글
Python관련 라이브러리 참고 사이트 정보 (0) | 2025.03.06 |
---|---|
간단한 기능 구현해보기(JSON) - (7) (3) | 2025.03.06 |
간단한 기능 구현해보기(XML) - (6) (1) | 2025.03.06 |
간단한 기능 구현해보기(파일 입출력) - (5) (0) | 2025.03.05 |
간단한 기능 구현해보기(함수) - (4) (0) | 2025.03.05 |