프로그래밍/파이썬

파이썬(Python), 정규식으로 제어 문자와 불필요한 공백 제거하기

dang_dang 2025. 3. 15. 10:47
728x90

 

  • 제어 문자가 무엇인지와 왜 제거해야 하는지
  • 정규식을 사용한 문자 제거 방법 설명
  • ASCII 제어 문자와 유니코드 제어 문자의 차이
  • 다양한 사용 사례(웹 입력, 데이터베이스 삽입, 로그 파일 처리 등)
  • 제가 제시한 추가 예제들의 활용법

 

import re

# 다양한 제어 문자와 공백이 포함된 문자열 예제들
examples = [
    " user\x07name ",               # 벨 문자
    "admin\t\r\n  ",                # 탭, 캐리지 리턴, 줄바꿈
    "\x1Fsecret\x1E\x00password",   # 다양한 제어 문자
    "email@\x08example.com",        # 백스페이스
    "\u200Bhidden\u200Btext",       # 제로 너비 공백(Zero Width Space)
]

# 1. 기본 ASCII 제어 문자 제거 (원래 코드와 동일)
def clean_basic(text):
    return re.sub(r'[\x00-\x1F\x7F]', '', text).strip()

# 2. 유니코드 제어 문자까지 제거 (더 포괄적)
def clean_unicode(text):
    return re.sub(r'[\x00-\x1F\x7F\u0080-\u009F\u200B-\u200F]', '', text).strip()

# 3. 모든 제어 문자 제거 (unicodedata 사용)
import unicodedata

def clean_all_control(text):
    return ''.join(ch for ch in text if unicodedata.category(ch)[0] != 'C').strip()

# 4. 탭과 줄바꿈은 유지하고 다른 제어 문자만 제거
def clean_preserve_whitespace(text):
    # \t, \n, \r은 제외하고 제어 문자 제거
    result = re.sub(r'[^\S\t\n\r]', ' ', text)  # 공백 표준화
    result = re.sub(r'[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]', '', result)
    return result.strip()

# 결과 출력
for i, example in enumerate(examples):
    print(f"예제 {i+1}:")
    print(f"원본: '{example}'")
    print(f"기본 정제: '{clean_basic(example)}'")
    print(f"유니코드 정제: '{clean_unicode(example)}'")
    print(f"모든 제어 문자 정제: '{clean_all_control(example)}'")
    print(f"공백 유지 정제: '{clean_preserve_whitespace(example)}'")
    print("-" * 50)
728x90