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

Tìm tất cả pattern "1(0+)1" trong chuỗi bằng Python Regex

Sử dụng module re (regular expression) để tìm tất cả lần xuất hiện của pattern 1(0+)1 trong chuỗi.

Ví dụ

Input: "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"
Output: 3 matches: ['1(0+)1', '1(0+)1', '1(0+)1']

Thuật toán

  1. Import module re.
  2. Khởi tạo chuỗi đầu vào.
  3. Compile regex pattern: re.compile(r"\d\(\d\+\)\d") (raw string quan trọng).
  4. Dùng findall() để lấy tất cả match.
  5. In số lượng và danh sách match.

Mã nguồn

import re

string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"

# Raw string r"" tránh escape backslash
regex = re.compile(r"\d\(\d\+\)\d")

result = regex.findall(string)

print(f"Total number of pattern matches are {len(result)}")
print(result)

Kết quả

Total number of pattern matches are 3
['1(0+)1', '1(0+)1', '1(0+)1']

Giải thích Pattern

RegexÝ nghĩa
\dKý tự số (0-9)
\( \)Ký tự '(' và ')' thật (escape)
\+Ký tự '+' thật (escape)
r""Raw string: không xử lý escape Python, giữ nguyên cho regex engine

Mở rộng: Tìm pattern số thực

# Tìm số dạng 1.0, 1.00, 1.000... (1 theo sau 1 hoặc nhiều 0 rồi 1)
pattern = r"1(0+)1"
# Ví dụ: "101 1001 10001 100001"
# Sử dụng group để lấy phần 0+
regex = re.compile(r"1(0+)1")
for match in regex.finditer("101 1001 10001"):
    print(f"Full: {match.group(0)}, Zeros: {match.group(1)}")

Kết luận

Module re mạnh mẽ cho tìm kiếm pattern phức tạp. Luôn dùng raw string r"" cho pattern. findall() trả về list string, finditer() trả về iterator match object (có vị trí, group).