기술(Tech, IT)/파이썬(Python)

[Tech, Python] re.escape

Daniel803 2024. 3. 2. 06:12

파이썬의 re 모듈에 있는 re.escape 함수는 문자열의 특수 문자를 escape 처리해 해당 문자가 특수 문자로 해석되지 않고 정규 표현식에서 사용될 수 있도록 설계됐다. "escape"라는 이름이 붙은 이유는 "escape"라는 더 넓은 프로그래밍 개념에서 유래했다.

 

많은 프로그래밍 언어와 문맥에서 "escape"한다는 것은 그 앞에 다른 문자 (종종 백슬래시 \)를 붙여 그 뒤에 오는 문자를 일반적인 특수 문자가 아닌 문자 그대로 해석해야 함을 나타낸다. 이는 정규식(다른 많은 구문과 마찬가지로)에서 특정 문자(.*?+()[]{}|^$ 등)가 수량화, 그룹화 또는 제어 구조를 나타내는 등 특별한 의미를 갖기 때문에 필요하다. 예시를 살펴보자.

 

  1. 기본적인 사용
    : text에서 "Hello, world!" 라는 정확한 문자열을 찾고 싶다고 가정하자. 느낌표(!)는 정규 표현식에서 특수 문자이므로 문자 그대로 일치시키려면 escape 처리를 해야한다.
    import re
    
    # String to search in
    text = "This is a test. Hello, world! Let's see if we can find 'Hello, world!'."
    
    # String you want to search for
    search_string = "Hello, world!"
    
    # Escape the search string to use it in a regular expression
    escaped_search_string = re.escape(search_string)
    
    # Compile a regular expression using the escaped string
    pattern = re.compile(escaped_search_string)
    
    # Search the text
    match = pattern.search(text)
    
    if match:
        print("Found:", match.group())
    else:
        print("Not found.")​
  2. 파일 경로 찾기
    : 파일 경로에는 백슬래시와 같이 정규식에서 특수한 문자가 포함된 경우가 많다. 문자열에서 특정 파일 경로를 찾는 경우 이러한 문자를 escape 처리해야 한다. 아래 코드에서 re.escape는 백슬래시(\\) 및 정규식 엔진이 잘못 해석할 수 있는 파일 경로의 기타 문자를 escape 처리하는 데 사용된다.
    import re
    
    # A string that contains file paths
    text = "The config file is located at C:\\Program Files\\MyApp\\config.txt. Please update it."
    
    # The file path to search for
    file_path = "C:\\Program Files\\MyApp\\config.txt"
    
    # Escape the file path
    escaped_file_path = re.escape(file_path)
    
    # Search for the escaped file path in the text
    match = re.search(escaped_file_path, text)
    
    if match:
        print("File path found in text.")
    else:
        print("File path not found.")​
  3. 동적 정규식
    : 사용자 입력이나 변수 내용을 기반으로 동적으로 정규식을 만들 때 re.escape를 사용하면 특수 문자로 인한 예기치 않은 동작이나 오류를 방지할 수 있다.
import re

# User input that might contain special characters
user_input = "[Important] Update!"

# Escape the user input
escaped_input = re.escape(user_input)

# Use the escaped input in a regex pattern
pattern = f"^{escaped_input}$"  # Matches the exact input only

# Example text to match against
text = "[Important] Update!"

# Search for the pattern
if re.match(pattern, text):
    print("Exact match found.")
else:
    print("No exact match.")

 

 

참고

- https://docs.python.org/3/library/re.html

- https://ihp001.tistory.com/142