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

Cách khớp mẫu và chuỗi với module RegEx trong Python

Giới thiệu

RegEx (Regular Expressions) dùng để tìm kiếm và thay thế theo mẫu. Ứng dụng: trình soạn thảo, tìm kiếm web, word processor... Ví dụ: trang web trường chỉ cho email đuôi @university.edu.

Bắt đầu

Module re có sẵn trong Python.

import re

Các hàm quan trọng

re.compile(pattern, flags)      # Biên dịch pattern
re.search(pattern, string, flags) # Tìm khớp trong chuỗi
re.match(pattern, string, flags)  # Kiểm tra khớp từ đầu chuỗi
re.split(pattern, string, max, flag) # Tách chuỗi theo pattern
re.findall(pattern, string, flag)   # Trả về tất cả match
re.finditer(pattern, string, flags) # Trả về iterator
re.sub(pattern, repl, string, count) # Thay thế
re.subn(pattern, repl, string, count) # Thay thế + trả tuple (string, count)
re.escape(pattern)                 # Escape ký tự đặc biệt

Ví dụ re.compile và re.match

x = re.compile("Hello world")
y = x.match("Hello world! How are things going?")
if y: print("Strings match")
else: print("Strings do not match")
Strings match

Có thể bỏ compile: re.match("Hello world", "Hello world! How are things going?")

re.split

x = re.split("\W+", "Hello,World")
print(x)  # ['Hello', 'World']
x = re.split("(\W+)", "Hello,World")
print(x)  # ['Hello', ',', 'World']

\W+: tách từ trái sang phải, + tiếp tục đến cuối. Có ngoặc thì giữ dấu câu.

re.sub và re.subn

x = re.sub(r"there", "World", "Hello there. Python is fun.")
print(x)  # Hello World. Python is fun.
x = re.subn(r"there", "World", "Hello there. Python is fun. Hello there")
print(x)  # ('Hello World. Python is fun. Hello World', 2)

Ví dụ thực tế: Validate mật khẩu

import re
matching_sequence = r"[0-9]"
while True:
    x = input("Nhập mật khẩu: ")
    r = re.search(matching_sequence, x)
    if r and len(x) > 6:
        print(x + " là mật khẩu hợp lệ")
    else:
        print(x + " KHÔNG hợp lệ. Phải ≥7 ký tự, có ít nhất 1 số")
    input("Nhấn Enter để thoát")

Kết luận

Đã nắm cơ bản RegEx. Xem thêm tại tài liệu chính thức.