Python Intermediate Lesson 6: Regular Expressions for UPI, GSTIN and PAN

Python Intermediate Lesson 6: Regular Expressions for UPI, GSTIN and PAN 1

πŸ“Ž This article includes 3 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ Python Intermediate Course Β· Lesson 6 of 10

Advertisement
In this article
  1. Parse a UPI narration with named groups
  2. Validate GSTIN and PAN
  3. Common mistakes
  4. Practice

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.

πŸ’‘ Write 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: match anchors at the start; search looks 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.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *