Regex (Regular Expressions)
Python tutorial · PySpark.in
Regular Expressions (Regex)
Regular Expressions (Regex) are powerful tools used for pattern matching and text processing. In Python, regex allows developers to search, validate, extract, and manipulate text efficiently.
Python provides built-in support for regex through the re module.
Regex is widely used in:
- Form validation
- Data extraction
- Log analysis
- Web scraping
- Input filtering
- Text cleaning
Why Use Regex?
Regex helps when you need to:
✔ Check if input matches a pattern
✔ Find specific words in large text
✔ Extract emails, phone numbers, URLs
✔ Replace text automatically
Example use cases:
- Email validation
- Password rules
- Website URL checking
- Removing unwanted characters
Python re Module
To use regex in Python:
```
Hide
import re
```
Basic Regex Patterns
Pattern | Meaning |
|---|---|
. | Any character |
\d | Digit (0–9) |
\w | Word character |
\s | Whitespace |
^ | Start of string |
$ | End of string |
* | 0 or more |
+ | 1 or more |
? | Optional |
Important Functions
re.search()
Finds first match in string.
```
import re
text = "Python is powerful"
result = re.search("Python", text)
print(result)
```
re.findall()
Returns all matches.
```
text = "apple banana apple"
print(re.findall("apple", text))
```
re.match()
Matches only at the beginning.
```
X=re.match("Hello", "Hello World")
print(X)
```
re.sub()
Replaces text.
```
text = "I love cats"
print(re.sub("cats", "dogs", text))
```
Practical Examples
Email Validation
```
import re
email = "user@gmail.com"
pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"
print(bool(re.match(pattern, email)))
```
Extract Numbers
```
text = "Marks: 85 and 92"
print(re.findall(r"\d+", text))
```
Website URL Validation
```
url = "https://www.google.com"
pattern = r"^(https?:\/\/)?(www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$"
print(bool(re.match(pattern, url)))
```
Advantages of Regex
✔ Saves time in text processing
✔ Handles complex search patterns
✔ Useful in real-world applications
✔ Essential skill for developers
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges