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)
