Python

크롤링 (문자열의 집합을 표현하는 정규 표현식)

usop 2023. 2. 1. 11:05

특정 문자(조건)를 포함한 항목과 아닌 항목을 나누어 보자

import re

# 문제1 ) 문자 a 또는 c로 시작하고, 이후 숫자 또는 알파벳이 4개로 끝나는 항목

list = ['ab123', 'cd4#6', 'cf79a', 'abc1']

regex = '[ac]{1}\w{4}'
pattern = re.compile(regex)

totallist = []

for item in list :
    if pattern.match(item) :
        print(item, '은(는) 조건에 적합')
        totallist.append(item)
    
    else :
        print(item, '은(는) 조건에 부적합')

        
print('적합한 항목들')
print(totallist)