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

FlyFeditv

๐Ÿ“˜ Introduction In this project, youโ€™ll create a command-line Expense Tracker that allows users to: โœ… Add expenses with category, amount, and descriptionโœ… View total spending and category breakdownโœ… Automatically…

Read more

NetCinFly

๐Ÿ“˜ Introduction In this project, youโ€™ll develop a Student Grades Analyzer in Python that can: This project helps you strengthen your skills with lists, dictionaries, loops, and data analysis logic….

Read more

Eagle_Pro

๐ŸŒ Introduction In this project, youโ€™ll create a Web Scraper App in Python that extracts quotes, authors, and tags from a live website.Youโ€™ll use the BeautifulSoup and Requests libraries to…

Read more

Cobra_Pro

๐ŸŒฆ๏ธ Introduction In this project, youโ€™ll build a Weather App in Python that retrieves live weather information from an online API.Youโ€™ll learn how to work with HTTP requests, JSON data,…

Read more

Show7-Pro

Concepts Covered: ๐ŸŽฏ Objective: Create a simple, text-based contact book application that allows users to: ๐Ÿ’ก Code (contact_book.py): ๐Ÿง  Example Usage Console Output Example: ๐Ÿ’พ Notes โฌ‡๏ธ Download Show7-Pro ุชุญู…ูŠู„…

Read more

Rapid_tv

๐Ÿ”น Introduction The Rock, Paper, Scissors Game is a classic hand game that you can easily build in Python. ๐Ÿ‘‰ Rules: ๐Ÿ”น Code Example ๐Ÿ”น Example Run ๐Ÿ”น Concepts Learned…

Read more