SwadhyAI Notes

All Python notes

Python RegEx 🔍

Regular Expressions

A RegEx is a sequence of characters that forms a search pattern. Python has a built-in package called re for working with Regular Expressions.

🕵️ Analogy: The Detective

Think of RegEx as a Detective's Description.
- Instead of searching for "John Smith" (exact match), you search for "A person with a name starting with J, 4 letters long, followed by a space..."
- It allows you to find patterns rather than just specific words.

✨ Common Functions

findall()

Returns a list containing all matches.

python
import re
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x) # ['ai', 'ai']

search()

Returns a Match object if there is a match.

python
txt = "The rain in Spain"
x = re.search("s", txt)
print(x.start()) # 3

split()

Returns a list where the string has been split at each match.

python
txt = "The rain in Spain"
x = re.split("s", txt)
print(x) # ['The', 'rain', ...

sub()

Replaces one or many matches with a string.

python
txt = "The rain in Spain"
x = re.sub("s", "9", txt)
print(x) # The9rain9in9Spain

🧩 Special Sequences

\d: Digit (0-9)
\D: Non-digit
\w: Word char (a-z, 0-9, _)
\W: Non-word char
\s: Whitespace
\S: Non-whitespace
^: Starts with
$: Ends with

🎯 Real-World Application: Email Validation

RegEx is constantly used to validate user input, like checking if an email address is valid.

python
import re

def is_valid_email(email):
    pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+
quot;
return bool(re.search(pattern, email)) print(is_valid_email("test@example.com")) # True print(is_valid_email("invalid-email")) # False

✨ Pro Tip: Raw Strings

Always use raw strings (r"pattern") for regex patterns. This tells Python not to treat backslashes as escape characters (like \n for newline).

python
# Bad
pattern = "\d+"

# Good
pattern = r"\d+"