
π This article includes 3 downloadable practice files β
A regular expression describes the shape of text. Python’s re module matches, extracts and replaces with it.
Parse a UPI narration with named groups
UPI = re.compile(r"^UPI/(?P<dir>DR|CR)/(?P<ref>\d{12})/(?P<payee>[^/]+)/"
r"(?P<bank>[A-Z]{4})/(?P<vpa>[^/]+)/(?P<note>.*)$")
m = UPI.match("UPI/DR/412345678901/SWIGGY/YESB/swiggy@ybl/Dinner")
m["payee"], m["vpa"], m["ref"] # 'SWIGGY', 'swiggy@ybl', '412345678901'
| Piece | Means |
|---|---|
\d{12} |
exactly 12 digits |
[^/]+ |
one or more characters that are not a slash |
(?P<name>...) |
a named group you read as m["name"] |
^ ... $ |
the whole line, start to end |
Validate GSTIN and PAN
GSTIN = re.compile(r"^\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$")
PAN = re.compile(r"^[A-Z]{5}\d{4}[A-Z]$")
A GSTIN is a 2-digit state code, the 10-character PAN, an entity number, the letter Z and a check character. The pattern checks the shape, not whether the GSTIN is registered or the check digit is right; use the GST portal for that.
r"..." (raw strings) for patterns so \d reaches the regex engine unchanged. Test patterns on regex101.com with the Python flavour.Common mistakes
- match vs search:
matchanchors at the start;searchlooks anywhere. - Greedy .* swallows too much; prefer
[^/]+style classes.
Practice
Unzip the practice data into a folder, put this lesson’s script in the same folder and run it (python pyi-NN.py). Compare with the expected output file. Then change one thing (a filter, a column, a format) and predict the new output before you run it.
π Practice files for this article
β¬ Download all 3 files (ZIP Β· 4 KB)
- πLesson 6 scriptThe complete script from this lesson, ready to run.β¬ PY Β· 1 KB
- πExpected outputWhat the script printed when we ran it, to compare with yours.β¬ TXT Β· 627 B
- ποΈPractice data (zip)sales.csv (120 invoices, 2 deliberately broken rows), customers.csv, products.json, statement.txt, rates.json and 3 monthly CSVs.β¬ ZIP Β· 4 KB
Free to use for learning. Files with macros (.bas) are plain text β import them with Alt+F11 β File β Import File, and always test on a copy.
Stuck on a step? Ask a question and the AI answers using this article.