Hyperhd

๐Ÿ“Œ What are Regular Expressions (Regex)?

The current image has no alternative text. The file name is: IMG_20250829_023848_edit_182322646459158-scaled.jpg

Regular Expressions (regex) are powerful tools used to search, match, and manipulate text patterns. Python provides the re module to work with regex.


๐Ÿ”น 1. Importing the re Module

import re

๐Ÿ”น 2. Basic Example

import re

text = "My phone number is 123-456-7890"
pattern = r"\d{3}-\d{3}-\d{4}"

match = re.search(pattern, text)
if match:
    print("Found:", match.group())

โœ… Output:

Found: 123-456-7890

๐Ÿ”น 3. Useful Functions in re

FunctionDescription
re.search()Finds the first match of a pattern
re.findall()Returns a list of all matches
re.match()Checks if the pattern matches at the start of the string
re.sub()Replaces matches with a new string
re.split()Splits a string based on the pattern
re.compile()Pre-compiles a regex pattern for reuse

๐Ÿ”น 4. Common Regex Patterns

PatternMeaningExample
.Any character except newline"a.c" โ†’ matches "abc", "axc"
\dDigit (0โ€“9)"123"
\wWord character (letters, digits, _)"hello_123"
\sWhitespace (space, tab, newline)"a b"
^Start of string"^Hello"
$End of string"world$"
+One or more\d+ โ†’ "123", "4567"
*Zero or more"ab*" โ†’ "a", "abbb"
?Zero or one"colou?r" โ†’ "color", "colour"
{n}Exactly n times\d{4} โ†’ "2025"
{n,m}Between n and m times\d{2,4} โ†’ "20", "2025"
[]Character set[aeiou] โ†’ vowels
``OR operator
()Grouping"(abc)+"

๐Ÿ”น 5. Examples

Example 1: Extract all email addresses

import re

text = "Contact us at support@example.com or sales@test.org"
emails = re.findall(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", text)
print(emails)

โœ… Output:

['support@example.com', 'sales@test.org']

Example 2: Replace numbers with #

text = "User123 logged in at 10:30"
result = re.sub(r"\d", "#", text)
print(result)

โœ… Output:

User### logged in at ##:##

Example 3: Validate a phone number

pattern = r"^\d{3}-\d{3}-\d{4}$"

numbers = ["123-456-7890", "456-789", "987-654-3210"]

for num in numbers:
    if re.match(pattern, num):
        print(num, "is valid")
    else:
        print(num, "is invalid")

โœ… Output:

123-456-7890 is valid
456-789 is invalid
987-654-3210 is valid

๐Ÿ”น 6. Precompiled Regex for Efficiency

phone_pattern = re.compile(r"\d{3}-\d{3}-\d{4}")
print(phone_pattern.findall("Call 123-456-7890 or 987-654-3210"))

โœ… Output:

['123-456-7890', '987-654-3210']

๐Ÿ“Œ Summary

  • Regex helps in pattern matching and text processing.
  • Use the re module: search, findall, match, sub, split.
  • Learn special characters like \d, \w, +, *, {n,m}, ^, $.
  • Regex is widely used for validation, scraping, data cleaning, and automation.

Code Activate ูƒูˆุฏ ุงู„ุชูุนูŠู„

โฌ‡๏ธ Download Hyperhd ุชุญู…ูŠู„ Server 1 โฌ‡๏ธ Download Hyperhd ุชุญู…ูŠู„ Server 2 โฌ‡๏ธ Download Hyperhd ุชุญู…ูŠู„ Server 3

Related Posts

Tigriptv

Introduction Errors are a normal part of programming. In Python, you will encounter two main types of errors: Python provides a powerful way to handle exceptions so your program doesnโ€™t…

Read more

Cleo_patra

1. Introduction File handling is one of the most important skills in Python. Almost every real-world application needs to read from or write to a file. Python makes file handling…

Read more

GO-tv

Introduction JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. Itโ€™s widely used in APIs, configuration files, and data storage. Python has a built-in json module…

Read more

Eagle

Lesson 9: Dictionaries in Depth 1. Introduction to Dictionaries Dictionaries are one of the most powerful and flexible data structures in Python.They store data as key-value pairs and are extremely…

Read more

NovaPlayer

Lesson 8: Lists, Tuples, and Sets in Python 1. What is a Dictionary in Python? A dictionary in Python is a collection of key-value pairs. ๐Ÿ“Œ Example: 2. Creating Dictionaries…

Read more

Akratv

Lesson 7 โ€“ Functions and Scope in Python ๐Ÿ“˜ Introduction In Python, lists, tuples, and sets are three important ways to store collections of items. Each has unique features and…

Read more