Python RegEx
🔍 Python RegEx (Regular Expressions)
A Regular Expression (RegEx) is a sequence of characters used to match patterns in text — such as emails, mobile numbers, dates, names, etc.
Python provides a built-in module for RegEx:
✔️ Common RegEx Methods in Python
| Function | Description |
|---|---|
re.search() | Searches for the first match |
re.findall() | Returns all matches |
re.match() | Checks if the pattern starts at the beginning of the string |
re.split() | Splits string by pattern |
re.sub() | Replaces matches |
📌 1. re.search() Example
📌 2. re.findall() Example
📌 3. re.match() Example
📌 4. re.split() Example
📌 5. re.sub() Example (Replace Text)
🧠 RegEx Metacharacters
| Pattern | Meaning | Example |
|---|---|---|
. | Any character except newline | he..o → hello |
^ | Starts with | ^Hello |
$ | Ends with | world$ |
* | 0 or more repetitions | go* → g, go, gooo |
+ | 1 or more repetitions | go+ → go, goo |
? | Optional | colou?r → color, colour |
{n} | Exactly n occurrences | \d{5} |
{n,m} | Between n and m repetitions | \d{2,4} |
🔢 Character Classes
| Pattern | Meaning |
|---|---|
\d | Matches digits (0-9) |
\D | Non-digit characters |
\s | Spaces |
\S | Non-spaces |
\w | Letters, numbers, underscore |
\W | Anything except letters/numbers/_ |
Example:
🎯 Using Groups ( )
📞 Real-World Examples
✔️ Validate Email
✔️ Validate Indian Phone Number
✔️ Extract All Numbers from Text
✔️ Check If String Only Contains Letters
📌 Summary Table
| Task | Function |
|---|---|
| Find first match | re.search() |
| Find all matches | re.findall() |
| Check beginning match | re.match() |
| Replace text | re.sub() |
| Split text | re.split() |
🧪 Practice Tasks
✔ Find all email addresses in text
✔ Validate password: must include letters, numbers, and symbols
✔ Extract dates (DD/MM/YYYY)
