هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.
$ مستخدم عادي# بصلاحية root (أو مع sudo)
Search and match
re.search finds the first match anywhere; re.fullmatch checks the whole string.
import re
line = "Oct 27 12:44:01 server1 sshd[6731]: Failed password for root from 203.0.113.50 port 51122 ssh2"
m = re.search(r"from (\d{1,3}(?:\.\d{1,3}){3}) port (\d+)", line)
if m:
print(m.group(1), m.group(2))
print(bool(re.fullmatch(r"[a-z][a-z0-9-]{2,30}", "web-01")))تذكّر
Always write patterns as raw strings (r"..."), so \d is not changed by Python first.
Find all matches
re.findall returns every match; re.finditer gives match objects one by one (good for big texts).
import re
from collections import Counter
text = open("/var/log/secure", encoding="utf-8", errors="replace").read()
ips = re.findall(r"Failed password for \S+ from (\S+)", text)
for ip, count in Counter(ips).most_common(5):
print(f"{count:5} {ip}")Use named groups
Name the parts of a pattern — the code becomes readable.
import re
pattern = re.compile(
r"(?P<ip>\S+) \S+ \S+ \[(?P<time>[^\]]+)\] \"(?P<method>\w+) (?P<path>\S+) [^\"]+\" (?P<status>\d{3}) (?P<size>\d+|-)"
)
line = '203.0.113.9 - - [27/Oct/2026:12:01:02 +0300] "GET /admin HTTP/1.1" 403 199'
m = pattern.match(line)
if m:
d = m.groupdict()
print(d["ip"], d["path"], d["status"])Replace and split
re.sub replaces with a pattern — for example to hide data before you share a log.
import re
log = "user=anna ip=10.0.0.5 token=abc123def"
masked = re.sub(r"token=\S+", "token=***", log)
anon = re.sub(r"\b\d{1,3}(\.\d{1,3}){3}\b", "x.x.x.x", masked)
print(anon)
print(re.split(r"[,;\s]+", "web1, web2;db1 cache1"))| Flag | Meaning |
|---|---|
re.IGNORECASE (re.I) | Ignore big/small letters |
re.MULTILINE (re.M) | ^ and $ match at every line |
re.VERBOSE (re.X) | Allow spaces and comments in the pattern |