Python Regular Expressions and File Operations Guide

Email Validation with Regular Expressions

To validate email addresses, we need to check that the username part contains only allowed characters (alphanumeric, hyphen, and underscore) and that the domain follows standard naming conventions. The domain should end with .com, .org, or .edu.

Example valid email: john_doe-123@example.com

import re

def validate_email(email_input):
    # Pattern explanation:
    # ^[a-zA-Z0-9_-]+ - Username part: starts with alphanumeric, underscore, or hyphen
    # @ - The @ symbol
    # [a-zA-Z0-9]+ - Domain name part
    # \.(com|org|edu)$ - Top-level domain
    pattern = r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9]+\.(com|org|edu)$'
    
    if re.match(pattern, email_input):
        return True
    return False

# Test cases
test_emails = [
    'john_doe@example.com',
    'user-123@test.org',
    'invalid@domain.net',
    'bad email@format.com'
]

for email in test_emails:
    result = 'Valid' if validate_email(email) else 'Invalid'
    print(f'{email}: {result}')

Generating User Credentials

Let's create a function to generate random usernames and passwords with specific requirements. Usernames should be 8-32 characters with underscores allowed, and passwords should be 8-16 characters with special characters permitted.

import random
import string

def generate_credentials():
    # Username generation
    username_length = random.randint(8, 32)
    username_chars = string.ascii_letters + string.digits + '_'
    username = ''.join(random.choice(username_chars) for _ in range(username_length))
    
    # Password generation
    password_length = random.randint(8, 16)
    # Include letters, digits, and special characters
    password_chars = string.ascii_letters + string.digits + '!@#$%^&*()_+-=[]{}|;:,.<>?'
    password = ''.join(random.choice(password_chars) for _ in range(password_length))
    
    return username, password

# Generate and display credentials
username, password = generate_credentials()
print(f'Username: {username}')
print(f'Password: {password}')

Password Hashing with MD5

For security, passwords should be stored as hashes rather than plain text. MD5 provides a one-way hashing function that converts any password into a fixed-langth hexadecimal string.

import hashlib

def hash_password(password_text):
    # Create MD5 hash object
    md5_hash = hashlib.md5()
    # Encode password to bytes and update hash
    md5_hash.update(password_text.encode('utf-8'))
    # Return hexadecimal representation
    return md5_hash.hexdigest()

def save_user_data(username, password, filename='credentials.txt'):
    # Hash the password
    hashed_pass = hash_password(password)
    
    # Write to file
    with open(filename, 'w') as file_handle:
        file_handle.write(f'Username: {username}\n')
        file_handle.write(f'Original Password: {password}\n')
        file_handle.write(f'Hashed Password: {hashed_pass}\n')

# Example usage
username, password = generate_credentials()
save_user_data(username, password)
print('User data saved successfully.')

Adavnced Text Processing

This section demonstrates comprehensive text processing using regular expressions. The requirements include:

  • Remove punctuation marks (, . ! ? : ;)
  • Replace all numbers with ==NUMBER==
  • Convert uppercase to lowercase
  • Remove leading spaces from each line
  • Condense multiple spaces into single spaces
  • Mark empty lines with [REMOVED]
import re

def process_text_file(input_path, output_path):
    # Compile all regex patterns for efficiency
    patterns = {
        'punctuation': re.compile(r'[,.!??:;]'),
        'numbers': re.compile(r'-?\d+\.?\d*'),
        'leading_spaces': re.compile(r'^\s+'),
        'multiple_spaces': re.compile(r'\s+')
    }
    
    with open(input_path, 'r', encoding='utf-8') as infile, \
         open(output_path, 'w', encoding='utf-8') as outfile:
        
        for line_num, original_line in enumerate(infile, 1):
            # Process each transformation step
            processed = patterns['punctuation'].sub('', original_line)
            processed = patterns['numbers'].sub('==NUMBER==', processed)
            processed = patterns['leading_spaces'].sub('', processed)
            processed = patterns['multiple_spaces'].sub(' ', processed)
            processed = processed.lower()
            
            # Check if line is empty after processing
            if not processed.strip():
                processed = '[REMOVED]\n'
            
            # Remove trailing newline if not [REMOVED]
            if processed != '[REMOVED]\n':
                processed = processed.rstrip() + '\n'
            
            outfile.write(processed)
            print(f'Processed line {line_num}: {original_line.strip()} -> {processed.strip()}')

# Example usage
# process_text_file('input.txt', 'output.txt')

Regular Expression Patterns Reference

Here are some useful regex patterns and their meanings:

  • \d - Matches any digit [0-9]
  • \D - Matches any non-digit character
  • \s - Matches any whitespace character
  • \S - Matches any non-whitespace character
  • \w - Matches any word character [a-zA-Z0-9_]
  • \W - Matches any non-word character
  • * - Matches zero or more occurrences
  • + - Matches one or more occurrences
  • ? - Matches zero or one occurrence
  • {m,n} - Matches between m and n occurrences
  • | - Acts as OR operator between expressions

Posted on Sat, 25 Jul 2026 17:07:44 +0000 by alexks