Jihun Oh

re 본문

Engineering/Python

re

Jihun Oh 2025. 4. 5. 07:55

re(정규표현식)을 사용해서

 

 

숫자와 소문자만 추출

import re

# 숫자와 소문자만 추출 (한 글자씩)
text = "Hello123! ABCdef456@#"
matches = re.findall(r'[a-z0-9]', text)
print(matches)  # ['e', 'l', 'l', 'o', '1', '2', '3', 'd', 'e', 'f', '4', '5', '6']

# 숫자와 소문자만 추출 (한 단어씩)
text = "A man, a plan, a canal: Panama"
matches = re.findall(r'[a-z0-9]+', text)
print(matches)  # ['man', 'a', 'plan', 'a', 'canal', 'anama']

# 단어의 순서를 뒤집어서 문장 만들기 (위에 연속)
text = "the sky is blue"
matches = re.findall(r'[a-zA-Z0-9]+', text)
result = ' '.join(matches[::-1])
print(result)


# 문자열을 소문자로 변환 후, 소문자, 숫자만 남기고 나머지 제거 (sub 이용)
text = "A man, a plan, a canal: Panama"
matches = re.sub(r'[^a-z0-9]', '', text.lower())
print(matches)  # 'amanaplanacanalpanama'

 

 

 

'Engineering > Python' 카테고리의 다른 글

Python 코드 정적 분석 도구  (0) 2025.06.15
itertools  (0) 2025.04.05
collections (defaultdict, Counter, OrderedDict, deque, namedtuple)  (0) 2024.05.15
generator  (0) 2024.04.14
set, tuple  (0) 2024.04.14