Exemplos de Processamento de Strings Web Rust

Exemplos de processamento de strings Web Rust incluindo divisão/junção de strings, regex e operações de substituição

💻 Divisão/Junção de Strings rust

🟢 simple ⭐⭐

Dividir strings por delimitadores e juntar coleções de strings com separadores

⏱️ 15 min 🏷️ rust, web, string processing
Prerequisites: Basic Rust
// Web Rust String Split/Join Examples
// String manipulation using split and join operations

// 1. Basic String Splitting

/// Split string by whitespace
fn split_by_whitespace(text: &str) -> Vec<&str> {
    text.split_whitespace().collect()
}

/// Split string by a specific delimiter
fn split_by_delimiter(text: &str, delimiter: &str) -> Vec<&str> {
    text.split(delimiter).collect()
}

/// Split string by multiple delimiters
fn split_by_multiple_delimiters(text: &str, delimiters: &[char]) -> Vec<&str> {
    text.split(|c: char| delimiters.contains(&c)).collect()
}

/// Split string and keep delimiters
fn split_keep_delimiter(text: &str, delimiter: &str) -> Vec<String> {
    let mut result = Vec::new();
    let mut last_pos = 0;

    while let Some(pos) = text[last_pos..].find(delimiter) {
        let absolute_pos = last_pos + pos;
        result.push(text[last_pos..absolute_pos].to_string());
        result.push(delimiter.to_string());
        last_pos = absolute_pos + delimiter.len();
    }

    if last_pos < text.len() {
        result.push(text[last_pos..].to_string());
    }

    result
}

// 2. Advanced Splitting

/// Split string into lines
fn split_into_lines(text: &str) -> Vec<&str> {
    text.lines().collect()
}

/// Split string with limit (max n parts)
fn split_with_limit(text: &str, delimiter: &str, n: usize) -> Vec<&str> {
    text.splitn(n, delimiter).collect()
}

/// Split string into fixed-size chunks
fn split_into_chunks(text: &str, chunk_size: usize) -> Vec<String> {
    text.as_bytes()
        .chunks(chunk_size)
        .map(|chunk| std::str::from_utf8(chunk).unwrap_or("").to_string())
        .collect()
}

/// Split string and trim each part
fn split_and_trim(text: &str, delimiter: &str) -> Vec<String> {
    text.split(delimiter)
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

// 3. String Joining

/// Join strings with a separator
fn join_strings(strings: &[&str], separator: &str) -> String {
    strings.join(separator)
}

/// Join strings with newline
fn join_with_lines(strings: &[&str]) -> String {
    strings.join("\n")
}

/// Join strings with comma and space
fn join_with_comma(strings: &[&str]) -> String {
    strings.join(", ")
}

// 4. Advanced Joining

/// Join strings with index
fn join_with_index(strings: &[&str]) -> String {
    strings.iter()
        .enumerate()
        .map(|(i, s)| format!("{}. {}", i + 1, s))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Join strings into pairs
fn join_into_pairs(strings: &[&str], pair_separator: &str, element_separator: &str) -> String {
    strings.chunks(2)
        .map(|pair| pair.join(element_separator))
        .collect::<Vec<_>>()
        .join(pair_separator)
}

/// Join with prefix and suffix for each element
fn join_with_wrappers(strings: &[&str], separator: &str, prefix: &str, suffix: &str) -> String {
    strings.iter()
        .map(|s| format!("{}{}{}", prefix, s, suffix))
        .collect::<Vec<_>>()
        .join(separator)
}

// 5. String Parsing from Split

/// Parse key-value pairs from string
fn parse_key_values(text: &str, item_delimiter: &str, kv_delimiter: &str) -> Vec<(String, String)> {
    text.split(item_delimiter)
        .filter_map(|item| {
            let parts: Vec<&str> = item.splitn(2, kv_delimiter).collect();
            if parts.len() == 2 {
                Some((parts[0].trim().to_string(), parts[1].trim().to_string()))
            } else {
                None
            }
        })
        .collect()
}

/// Split and collect non-empty parts
fn split_non_empty(text: &str, delimiter: &str) -> Vec<&str> {
    text.split(delimiter)
        .filter(|s| !s.is_empty())
        .collect()
}

/// Split string into character array
fn split_into_chars(text: &str) -> Vec<char> {
    text.chars().collect()
}

// Usage Examples
fn main() {
    println!("=== Web Rust String Split/Join Examples ===\n");

    // 1. Basic splitting
    println!("--- 1. Basic Splitting ---");
    let text = "hello world rust programming";
    println!("Original: {}", text);
    println!("Split by whitespace: {:?}", split_by_whitespace(text));

    let text = "apple,banana,orange";
    println!("\nOriginal: {}", text);
    println!("Split by comma: {:?}", split_by_delimiter(text, ","));

    // 2. Multiple delimiters
    println!("\n--- 2. Multiple Delimiters ---");
    let text = "apple;banana:orange|grape";
    println!("Original: {}", text);
    println!("Split by [;,:|]: {:?}", split_by_multiple_delimiters(text, &[';', ':', '|']));

    // 3. Lines
    println!("\n--- 3. Split Lines ---");
    let text = "line1\nline2\nline3";
    println!("Original: {:?}", text);
    println!("Lines: {:?}", split_into_lines(text));

    // 4. Split with limit
    println!("\n--- 4. Split with Limit ---");
    let text = "one,two,three,four,five";
    println!("Original: {}", text);
    println!("Split (max 3 parts): {:?}", split_with_limit(text, ",", 3));

    // 5. Split and trim
    println!("\n--- 5. Split and Trim ---");
    let text = " apple , banana , orange ";
    println!("Original: '{}'", text);
    println!("Split and trim: {:?}", split_and_trim(text, ","));

    // 6. Chunks
    println!("\n--- 6. Split into Chunks ---");
    let text = "abcdefghij";
    println!("Original: {}", text);
    println!("Chunks of 3: {:?}", split_into_chunks(text, 3));

    // 7. Join strings
    println!("\n--- 7. Join Strings ---");
    let words = vec!["hello", "world", "rust"];
    println!("Words: {:?}", words);
    println!("Joined with '-': {}", join_strings(&words, "-"));
    println!("Joined with comma: {}", join_with_comma(&words));
    println!("Joined with lines: {}", join_with_lines(&words));

    // 8. Advanced joining
    println!("\n--- 8. Advanced Joining ---");
    let items = vec!["apple", "banana", "orange", "grape"];
    println!("Items: {:?}", items);
    println!("With index:\n{}", join_with_index(&items));
    println!("With wrappers: {}", join_with_wrappers(&items, ", ", "[", "]"));

    // 9. Parse key-values
    println!("\n--- 9. Parse Key-Value Pairs ---");
    let text = "name=John;age=30;city=NYC";
    println!("Original: {}", text);
    println!("Parsed: {:?}", parse_key_values(text, ";", "="));

    // 10. Characters
    println!("\n--- 10. Split into Characters ---");
    let text = "hello";
    println!("Original: {}", text);
    println!("Characters: {:?}", split_into_chars(text));

    println!("\n=== All String Split/Join Examples Completed ===");
}

💻 Expressões Regulares rust

🟡 intermediate ⭐⭐⭐

Correspondência de padrões e busca de texto usando regex em Rust

⏱️ 25 min 🏷️ rust, web, string processing, regex
Prerequisites: Intermediate Rust, regex crate
// Web Rust Regular Expressions Examples
// Pattern matching using regex crate
//
// Add to Cargo.toml:
// [dependencies]
// regex = "1.10"

use regex::Regex;

// 1. Basic Pattern Matching

/// Check if pattern matches string
fn is_match(text: &str, pattern: &str) -> Result<bool, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.is_match(text))
}

/// Find first match
fn find_first(text: &str, pattern: &str) -> Result<Option<regex::Match>, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.find(text))
}

/// Find all matches
fn find_all(text: &str, pattern: &str) -> Result<Vec<regex::Match>, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.find_iter(text).collect())
}

/// Extract matched text
fn extract_matches(text: &str, pattern: &str) -> Result<Vec<String>, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.find_iter(text)
        .map(|m| m.as_str().to_string())
        .collect())
}

// 2. Capture Groups

/// Extract capture groups
fn capture_groups(text: &str, pattern: &str) -> Result<Vec<Vec<String>>, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.captures_iter(text)
        .filter_map(|caps| {
            Some((1..caps.len())
                .filter_map(|i| caps.get(i).map(|m| m.as_str().to_string()))
                .collect())
        })
        .collect())
}

/// Extract named capture groups
fn capture_named_groups(text: &str, pattern: &str) -> Result<Vec<Vec<(String, String)>>, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.captures_iter(text)
        .filter_map(|caps| {
            Some(re.capture_names()
                .flatten()
                .filter_map(|name| {
                    caps.name(name).map(|m| (name.to_string(), m.as_str().to_string()))
                })
                .collect())
        })
        .collect())
}

/// Extract single group from first match
fn extract_first_group(text: &str, pattern: &str) -> Result<Option<String>, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.captures(text)
        .and_then(|caps| caps.get(1))
        .map(|m| m.as_str().to_string()))
}

// 3. Regex Operations

/// Count matches
fn count_matches(text: &str, pattern: &str) -> Result<usize, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.find_iter(text).count())
}

/// Split by regex
fn split_by_regex(text: &str, pattern: &str) -> Result<Vec<String>, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.split(text).map(|s| s.to_string()).collect())
}

/// Check if string contains pattern
fn contains_pattern(text: &str, pattern: &str) -> Result<bool, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.is_match(text))
}

// 4. Common Patterns

/// Validate email address
fn is_valid_email(email: &str) -> Result<bool, regex::Error> {
    let pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$";
    is_match(email, pattern)
}

/// Validate URL
fn is_valid_url(url: &str) -> Result<bool, regex::Error> {
    let pattern = r"^https?://[a-zA-Z0-9.-]+(.[a-zA-Z]{2,})?(/.*)?$";
    is_match(url, pattern)
}

/// Validate phone number (simple format)
fn is_valid_phone(phone: &str) -> Result<bool, regex::Error> {
    let pattern = r"^+?[ds-()]+$";
    is_match(phone, pattern)
}

/// Extract numbers from text
fn extract_numbers(text: &str) -> Result<Vec<i32>, regex::Error> {
    let re = Regex::new(r"-?d+")?;
    Ok(re.find_iter(text)
        .filter_map(|m| m.as_str().parse::<i32>().ok())
        .collect())
}

/// Extract words from text
fn extract_words(text: &str) -> Result<Vec<String>, regex::Error> {
    let re = Regex::new(r"[a-zA-Z]+")?;
    Ok(re.find_iter(text)
        .map(|m| m.as_str().to_string())
        .collect())
}

// 5. Text Manipulation with Regex

/// Remove all digits
fn remove_digits(text: &str) -> Result<String, regex::Error> {
    let re = Regex::new(r"d")?;
    Ok(re.replace_all(text, "").to_string())
}

/// Remove all whitespace
fn remove_whitespace(text: &str) -> Result<String, regex::Error> {
    let re = Regex::new(r"s+")?;
    Ok(re.replace_all(text, " ").to_string())
}

/// Extract hashtags
fn extract_hashtags(text: &str) -> Result<Vec<String>, regex::Error> {
    let re = Regex::new(r"#(w+)")?;
    Ok(re.find_iter(text)
        .map(|m| m.as_str().to_string())
        .collect())
}

/// Extract mentions
fn extract_mentions(text: &str) -> Result<Vec<String>, regex::Error> {
    let re = Regex::new(r"@(w+)")?;
    Ok(re.find_iter(text)
        .map(|m| m.as_str().to_string())
        .collect())
}

// 6. Advanced Patterns

/// Parse date (YYYY-MM-DD)
fn parse_date(text: &str) -> Result<Option<(u32, u32, u32)>, regex::Error> {
    let re = Regex::new(r"(d{4})-(d{2})-(d{2})")?;
    Ok(re.captures(text).and_then(|caps| {
        Some((
            caps.get(1)?.as_str().parse().ok()?,
            caps.get(2)?.as_str().parse().ok()?,
            caps.get(3)?.as_str().parse().ok()?,
        ))
    }))
}

/// Parse HTML tags (simple)
fn find_html_tags(text: &str) -> Result<Vec<String>, regex::Error> {
    let re = Regex::new(r"<(w+)")?;
    Ok(re.find_iter(text)
        .map(|m| m.as_str().to_string())
        .collect())
}

/// Extract IP addresses
fn extract_ip_addresses(text: &str) -> Result<Vec<String>, regex::Error> {
    let re = Regex::new(r"d{1,3}.d{1,3}.d{1,3}.d{1,3}")?;
    Ok(re.find_iter(text)
        .map(|m| m.as_str().to_string())
        .collect())
}

// 7. Regex with Case Insensitivity

/// Find matches ignoring case
fn find_case_insensitive(text: &str, pattern: &str) -> Result<Vec<String>, regex::Error> {
    let re = Regex::new(&format!("(?i){}", pattern))?;
    Ok(re.find_iter(text)
        .map(|m| m.as_str().to_string())
        .collect())
}

/// Check if word exists (case insensitive)
fn contains_word(text: &str, word: &str) -> Result<bool, regex::Error> {
    let pattern = format!(r"(?i){}", regex::escape(word));
    is_match(text, &pattern)
}

// Usage Examples
fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Web Rust Regular Expressions Examples ===\n");

    // 1. Basic matching
    println!("--- 1. Basic Matching ---");
    let text = "Hello, World! 123";
    println!("Text: {}", text);
    println!("Contains digits: {}", is_match(text, r"d")?);
    println!("Contains 'Hello': {}", is_match(text, r"Hello")?);

    // 2. Find matches
    println!("\n--- 2. Find Matches ---");
    let text = "Contact us at [email protected] or [email protected]";
    println!("Text: {}", text);
    let emails = extract_matches(text, r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}")?;
    println!("Emails found: {:?}", emails);

    // 3. Capture groups
    println!("\n--- 3. Capture Groups ---");
    let text = "John: 30, Jane: 25, Bob: 35";
    println!("Text: {}", text);
    let pattern = r"(w+):s*(d+)";
    let groups = capture_groups(text, pattern)?;
    println!("Name-Age pairs: {:?}", groups);

    // 4. Count matches
    println!("\n--- 4. Count Matches ---");
    let text = "apple banana apple orange apple";
    println!("Text: {}", text);
    println!("Count of 'apple': {}", count_matches(text, r"apple")?);

    // 5. Validation
    println!("\n--- 5. Validation ---");
    println!("Email validation:");
    println!("  [email protected]: {}", is_valid_email("[email protected]")?);
    println!("  invalid-email: {}", is_valid_email("invalid-email")?);

    println!("URL validation:");
    println!("  https://example.com: {}", is_valid_url("https://example.com")?);
    println!("  invalid-url: {}", is_valid_url("invalid-url")?);

    // 6. Extract data
    println!("\n--- 6. Extract Data ---");
    let text = "The numbers are 42, 100, and -5";
    println!("Text: {}", text);
    println!("Numbers: {:?}", extract_numbers(text)?);

    let text = "Hello world! This is a TEST.";
    println!("\nText: {}", text);
    println!("Words: {:?}", extract_words(text)?);

    // 7. Text manipulation
    println!("\n--- 7. Text Manipulation ---");
    let text = "Phone: 123-456-7890";
    println!("Original: {}", text);
    println!("Remove digits: {}", remove_digits(text)?);

    let text = "Too   much   whitespace";
    println!("\nOriginal: '{}'", text);
    println!("Normalize: '{}'", remove_whitespace(text)?);

    // 8. Social media
    println!("\n--- 8. Social Media ---");
    let text = "Check out @user1 and #rust! #programming @user2";
    println!("Text: {}", text);
    println!("Hashtags: {:?}", extract_hashtags(text)?);
    println!("Mentions: {:?}", extract_mentions(text)?);

    // 9. IP addresses
    println!("\n--- 9. Extract IP Addresses ---");
    let text = "Server IPs: 192.168.1.1, 10.0.0.1, and 8.8.8.8";
    println!("Text: {}", text);
    println!("IPs: {:?}", extract_ip_addresses(text)?);

    // 10. Case insensitive
    println!("\n--- 10. Case Insensitive ---");
    let text = "Hello HELLO heLlo";
    println!("Text: {}", text);
    println!("Contains 'hello' (case insensitive): {}", contains_word(text, "hello")?);

    println!("\n=== All Regex Examples Completed ===");
    Ok(())
}

💻 Substituição de Strings rust

🟡 intermediate ⭐⭐⭐

Buscar e substituir substrings com vários padrões e estratégias

⏱️ 20 min 🏷️ rust, web, string processing
Prerequisites: Intermediate Rust, regex crate
// Web Rust String Replacement Examples
// String replacement using various methods

use std::collections::HashMap;

// 1. Basic String Replacement

/// Replace first occurrence
fn replace_first(text: &str, from: &str, to: &str) -> String {
    text.replacen(from, to, 1)
}

/// Replace all occurrences
fn replace_all(text: &str, from: &str, to: &str) -> String {
    text.replace(from, to)
}

/// Replace first n occurrences
fn replace_n(text: &str, from: &str, to: &str, n: usize) -> String {
    text.replacen(from, to, n)
}

// 2. Case-Insensitive Replacement

/// Replace all occurrences (case insensitive)
fn replace_all_case_insensitive(text: &str, from: &str, to: &str) -> String {
    let pattern = format!("(?i){}", regex::escape(from));
    let re = regex::Regex::new(&pattern).unwrap();
    re.replace_all(text, to).to_string()
}

// 3. Multiple Replacements

/// Replace multiple patterns using closure
fn replace_multiple<F>(text: &str, replacements: F) -> String
where
    F: Fn(&str) -> String,
{
    text.split_whitespace()
        .map(replacements)
        .collect::<Vec<_>>()
        .join(" ")
}

/// Replace using map of patterns
fn replace_from_map(text: &str, replacements: &HashMap<&str, &str>) -> String {
    let mut result = text.to_string();
    for (from, to) in replacements {
        result = result.replace(from, to);
    }
    result
}

/// Replace sequentially
fn replace_sequential(text: &str, replacements: &[( &str, &str)]) -> String {
    let mut result = text.to_string();
    for (from, to) in replacements {
        result = result.replace(from, to);
    }
    result
}

// 4. Pattern-Based Replacement

/// Replace digits with placeholder
fn replace_digits(text: &str, placeholder: &str) -> String {
    let re = regex::Regex::new(r"d+").unwrap();
    re.replace_all(text, placeholder).to_string()
}

/// Replace words using closure
fn replace_words_with<F>(text: &str, f: F) -> String
where
    F: Fn(&str) -> String,
{
    let re = regex::Regex::new(r"w+").unwrap();
    re.replace_all(text, f).to_string()
}

/// Replace based on length
fn replace_by_length(text: &str, short_replacement: &str, long_replacement: &str) -> String {
    replace_words_with(text, |word: &str| -> String {
        if word.len() <= 3 {
            short_replacement.to_string()
        } else {
            long_replacement.to_string()
        }
    })
}

// 5. Template Replacement

/// Replace placeholders in template
fn replace_template(template: &str, data: &HashMap<String, String>) -> String {
    let mut result = template.to_string();
    for (key, value) in data {
        let placeholder = format!("{{{}}}", key);
        result = result.replace(&placeholder, value);
    }
    result
}

/// Replace placeholders with positional values
fn replace_positional(template: &str, values: &[&str]) -> String {
    let mut result = template.to_string();
    for (i, value) in values.iter().enumerate() {
        let placeholder = format!("{{{}}}", i);
        result = result.replace(&placeholder, value);
    }
    result
}

// 6. Advanced Replacement

/// Remove all punctuation
fn remove_punctuation(text: &str) -> String {
    let re = regex::Regex::new(r"[[:punct:]]").unwrap();
    re.replace_all(text, "").to_string()
}

/// Normalize whitespace
fn normalize_whitespace(text: &str) -> String {
    let re = regex::Regex::new(r"s+").unwrap();
    re.replace_all(text.trim(), " ").to_string()
}

/// Remove extra spaces
fn remove_extra_spaces(text: &str) -> String {
    let re = regex::Regex::new(r" +").unwrap();
    re.replace_all(text, " ").to_string()
}

/// Remove all spaces
fn remove_all_spaces(text: &str) -> String {
    text.replace(" ", "")
}

// 7. Text Cleanup

/// Clean text (normalize and trim)
fn clean_text(text: &str) -> String {
    normalize_whitespace(text).trim().to_string()
}

/// Remove specific characters
fn remove_chars(text: &str, chars_to_remove: &str) -> String {
    text.chars()
        .filter(|c| !chars_to_remove.contains(*c))
        .collect()
}

/// Keep only alphanumeric
fn keep_alphanumeric(text: &str) -> String {
    text.chars()
        .filter(|c| c.is_alphanumeric())
        .collect()
}

// 8. Conditional Replacement

/// Replace words based on condition
fn replace_if<F>(text: &str, condition: F, replacement: &str) -> String
where
    F: Fn(&str) -> bool,
{
    text.split_whitespace()
        .map(|word| {
            if condition(word) {
                replacement.to_string()
            } else {
                word.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Replace words starting with prefix
fn replace_words_starting_with(text: &str, prefix: &str, replacement: &str) -> String {
    replace_if(text, |word| word.starts_with(prefix), replacement)
}

/// Replace words ending with suffix
fn replace_words_ending_with(text: &str, suffix: &str, replacement: &str) -> String {
    replace_if(text, |word| word.ends_with(suffix), replacement)
}

// 9. URL Encoding/Decoding (simplified)

/// Percent encode special characters (simplified)
fn percent_encode(text: &str) -> String {
    text.chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '~' {
                c.to_string()
            } else {
                format!("%{:02X}", c as u8)
            }
        })
        .collect()
}

// 10. Masking and Sanitization

/// Mask email address
fn mask_email(email: &str) -> String {
    let re = regex::Regex::new(r"(.{2})[^@]+(@.+)").unwrap();
    re.replace(email, "$1***$2").to_string()
}

/// Mask credit card (keep last 4 digits)
fn mask_credit_card(card: &str) -> String {
    let re = regex::Regex::new(r"d{12}(d{4})").unwrap();
    re.replace(card, "************$1").to_string()
}

/// Mask phone number
fn mask_phone(phone: &str) -> String {
    let re = regex::Regex::new(r"(d{3})[s-]?d{3}[s-]?(d{4})").unwrap();
    re.replace(phone, "$1-***-$2").to_string()
}

// Usage Examples
fn main() {
    println!("=== Web Rust String Replacement Examples ===\n");

    // 1. Basic replacement
    println!("--- 1. Basic Replacement ---");
    let text = "hello world hello universe";
    println!("Original: {}", text);
    println!("Replace 'hello' with 'hi': {}", replace_all(text, "hello", "hi"));
    println!("Replace first 'hello' with 'hi': {}", replace_first(text, "hello", "hi"));

    // 2. Multiple replacements
    println!("\n--- 2. Multiple Replacements ---");
    let text = "I like apples and oranges";
    println!("Original: {}", text);
    println!("Replace 'apples'->'bananas', 'oranges'->'grapes': {}",
        replace_sequential(text, &[("apples", "bananas"), ("oranges", "grapes")]));

    // 3. Case insensitive
    println!("\n--- 3. Case Insensitive ---");
    let text = "Hello HELLO heLlo";
    println!("Original: {}", text);
    println!("Replace all 'hello' with 'hi': {}", replace_all_case_insensitive(text, "hello", "hi"));

    // 4. Pattern replacement
    println!("\n--- 4. Pattern Replacement ---");
    let text = "Phone: 123-456-7890";
    println!("Original: {}", text);
    println!("Replace digits: {}", replace_digits(text, "[REDACTED]"));

    // 5. Template replacement
    println!("\n--- 5. Template Replacement ---");
    let template = "Hello {name}, your order {order} is ready!";
    let mut data = HashMap::new();
    data.insert("name".to_string(), "John".to_string());
    data.insert("order".to_string(), "#12345".to_string());
    println!("Template: {}", template);
    println!("Filled: {}", replace_template(template, &data));

    // 6. Positional replacement
    println!("\n--- 6. Positional Replacement ---");
    let template = "Hello {0}, welcome to {1}!";
    println!("Template: {}", template);
    println!("Filled: {}", replace_positional(template, &["Alice", "Wonderland"]));

    // 7. Text cleanup
    println!("\n--- 7. Text Cleanup ---");
    let text = "  Too   many   spaces  \t here  ";
    println!("Original: '{}'", text);
    println!("Normalized: '{}'", normalize_whitespace(text));
    println!("Cleaned: '{}'", clean_text(text));

    // 8. Remove characters
    println!("\n--- 8. Remove Characters ---");
    let text = "Hello, World! How are you?";
    println!("Original: {}", text);
    println!("Remove punctuation: {}", remove_punctuation(text));
    println!("Keep alphanumeric: {}", keep_alphanumeric(text));

    // 9. Conditional replacement
    println!("\n--- 9. Conditional Replacement ---");
    let text = "The incredible amazing fantastic story";
    println!("Original: {}", text);
    println!("Replace long words (>5 chars): {}", replace_by_length(text, "short", "long"));

    // 10. Masking
    println!("\n--- 10. Masking ---");
    println!("Email: {}", mask_email("[email protected]"));
    println!("Credit card: {}", mask_credit_card("1234567890123456"));
    println!("Phone: {}", mask_phone("123-456-7890"));

    // 11. Percent encoding
    println!("\n--- 11. Percent Encoding ---");
    let text = "hello world!";
    println!("Original: {}", text);
    println!("Encoded: {}", percent_encode(text));

    println!("\n=== All String Replacement Examples Completed ===");
}