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

Cách dùng Wildcard (ký tự đại diện) trong Python Regex

Trong regex, ký tự chấm . là wildcard: khớp với bất kỳ ký tự đơn nào TRỪ newline.

Ví dụ cơ bản

import re

# 'th.s' khớp 'this', 'thus', 'thxs', 'th3s'... KHÔNG khớp 'th s' (space) hay 'th\ns'
pattern = r'th.s'
text = "this, thus, just, then, th s"

print(re.findall(pattern, text))
# ['this', 'thus']

Kết quả


['this', 'thus']

Flag re.DOTALL (re.S): Cho phép . khớp newline


text = "this\nthus"

print(re.findall(r'th.s', text))           # ['this'] - không khớp newline
print(re.findall(r'th.s', text, re.DOTALL)) # ['this', 'thus'] - khớp newline

Wildcard thực sự (bất kỳ ký tự kể cả newline) không cần flag


# [\s\S] hoặc [\d\D] hoặc [\w\W] - khớp mọi ký tự
re.findall(r'th[\s\S]s', "this\nthus")  # ['this\nthus']

Quantifier với Wildcard

PatternÝ nghĩa
.*0 hoặc nhiều ký tự (greedy)
.*?0 hoặc nhiều ký tự (non-greedy/lazy)
.+1 hoặc nhiều ký tự (greedy)
.+?1 hoặc nhiều ký tự (non-greedy)

Ví dụ: Extract giữa 2 delimiter


text = 'content1 content2'

# Greedy - khớp từ  đầu đến  cuối
print(re.findall(r'.*', text))
# ['content1 content2']

# Non-greedy - khớp từng cặp
print(re.findall(r'.*?', text))
# ['content1', 'content2']

Lưu ý

  • . KHÔNG khớp newline mặc định (khác với shell wildcard *).
  • Dùng re.DOTALL hoặc [\s\S] nếu cần khớp newline.
  • Luôn ưu tiên non-greedy .*? khi extract content giữa delimiters.