티스토리 뷰
파이썬의 re 모듈에 있는 re.escape 함수는 문자열의 특수 문자를 escape 처리해 해당 문자가 특수 문자로 해석되지 않고 정규 표현식에서 사용될 수 있도록 설계됐다. "escape"라는 이름이 붙은 이유는 "escape"라는 더 넓은 프로그래밍 개념에서 유래했다.
많은 프로그래밍 언어와 문맥에서 "escape"한다는 것은 그 앞에 다른 문자 (종종 백슬래시 \)를 붙여 그 뒤에 오는 문자를 일반적인 특수 문자가 아닌 문자 그대로 해석해야 함을 나타낸다. 이는 정규식(다른 많은 구문과 마찬가지로)에서 특정 문자(.*?+()[]{}|^$ 등)가 수량화, 그룹화 또는 제어 구조를 나타내는 등 특별한 의미를 갖기 때문에 필요하다. 예시를 살펴보자.
- 기본적인 사용
: 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.")
- 파일 경로 찾기
: 파일 경로에는 백슬래시와 같이 정규식에서 특수한 문자가 포함된 경우가 많다. 문자열에서 특정 파일 경로를 찾는 경우 이러한 문자를 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.")
- 동적 정규식
: 사용자 입력이나 변수 내용을 기반으로 동적으로 정규식을 만들 때 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.")
참고
반응형
'기술(Tech, IT) > 파이썬(Python)' 카테고리의 다른 글
[Tech, Python] re.group() (3) | 2024.03.13 |
---|---|
[Tech, Python] re.compile() (0) | 2024.03.08 |
[Python] raw strings (0) | 2024.01.07 |
[Python] SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape (0) | 2024.01.06 |
[Python] pickle (0) | 2023.12.28 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 안드로이드
- Hash Map
- 머신 러닝
- 소켓 프로그래밍
- Android
- tf-idf
- Computer Graphics
- I2C
- C++
- 투 포인터
- 딕셔너리
- join
- 오블완
- vertex shader
- machine learning
- 이코노미스트
- The Economist
- socket programming
- The Economist Espresso
- ml
- Python
- min heap
- defaultdict
- 파이썬
- leetcode
- java
- 리트코드
- 티스토리챌린지
- 이코노미스트 에스프레소
- DICTIONARY
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함
반응형