Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách escape tất cả ký tự đặc biệt cho Regex trong Python

Dùng re.escape(string) để escape tự động tất cả metacharacters trong string, biến nó thành literal pattern an toàn.

Ví dụ

import re

p = '5*(67).89?'
escaped = re.escape(p)
print(escaped)
# 5\*\(67\)\.89\?

Kết quả


5\*\(67\)\.89\?

Khi nào cần re.escape()

  • Pattern xây dựng từ user input.
  • Tìm kiếm literal string chứa metacharacters (. * + ? ^ $ [ ] { } ( ) | \).
  • Kết hợp literal string vào pattern động.

Ví dụ thực tế: Tìm từ khóa người dùng nhập


def search_literal(text, keyword):
    """Tìm keyword như literal string, không interpret as regex"""
    pattern = re.escape(keyword)
    return re.findall(pattern, text)

print(search_literal('Price: $100.50', '$100.50'))  # ['$100.50']
print(search_literal('Regex: a*b+c?', 'a*b+c?'))    # ['a*b+c?']

Kết hợp với pattern khác


keyword = 'error'
# Tìm dòng chứa keyword (literal)
pattern = rf'.*{re.escape(keyword)}.*'
# Hoặc đơn giản:
pattern = rf'.*{re.escape(keyword)}.*'

# Word boundary cho keyword
pattern = rf'\b{re.escape(keyword)}\b'

Các ký tự bị escape


import re
print(re.escape('.^$*+?{}[]\\|()'))  
# \.\^\$\*\+\?\{\}\[\]\\\|\(\)

Lưu ý: re.escape() escape tất cả non-alphanumeric characters. Từ Python 3.7, chỉ escape các ký tự có ý nghĩa đặc biệt trong regex (giữ lại ~, @, v.v.).