Elysia Tools

Explora herramientas, ejemplos, explicaciones visuales y guías temáticas en un solo espacio claro.

Categorías populares

Temas

Idioma
ZHDERUPTENFRES

Elysia Tools

Navegación

Rust

Ejemplos de Procesamiento de Cadenas Web Rust

Ejemplos de procesamiento de cadenas Web Rust incluyendo dividir/unir cadenas, regex y operaciones de reemplazo

Ejemplos

Entradas de esta colección

CódigorustSimple

Dividir/Unir Cadenas

Dividir cadenas por delimitadores y unir colecciones de cadenas con separadores

Dificultad

3/10

Tiempo estimado

15 min

Etiquetas

rust, web, string processing

Requisitos previos

Basic Rust

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 ===");
}
CódigorustIntermedio

Expresiones Regulares

Coincidencia de patrones y búsqueda de texto usando regex en Rust

Dificultad

6/10

Tiempo estimado

25 min

Etiquetas

rust, web, string processing, regex

Requisitos previos

Intermediate Rust, regex crate

rust
// 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<'a>(text: &'a str, pattern: &str) -> Result<Option<regex::Match<'a>>, regex::Error> {
    let re = Regex::new(pattern)?;
    Ok(re.find(text))
}

/// Find all matches
fn find_all<'a>(text: &'a str, pattern: &str) -> Result<Vec<regex::Match<'a>>, 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 info@example.com or support@test.org";
    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!("  test@example.com: {}", is_valid_email("test@example.com")?);
    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(())
}
CódigorustIntermedio

Reemplazo de Cadenas

Buscar y reemplazar subcadenas con varios patrones y estrategias

Dificultad

5/10

Tiempo estimado

20 min

Etiquetas

rust, web, string processing

Requisitos previos

Intermediate Rust, regex crate

rust
// 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("john.doe@example.com"));
    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 ===");
}

Herramientas

Herramientas que suelen usarse con este ejemplo

Relacionado

Colecciones de ejemplos relacionadas

Relacionado

Temas relacionados

Tema

Captura autorizada de webhooks y revisión de confianza del endpoint

Captura y repite solicitudes webhook controladas, revisa la evidencia de entrega y comprueba el certificado HTTPS del receptor sin confundir un certificado válido con confianza empresarial.

Tema

Depuracion de Observabilidad con Logs, Trazas, Webhooks y Payloads JSON

Parsea logs, decodifica trazas, revisa evidencia webhook/API, explora payloads JSON y extrae patrones recurrentes antes de redactar una nota de incidente.

Tema

Conversión de formatos para entrega de video: audio, streams, GIF, WebM y MP4

Define el destino de entrega, extrae solo el stream necesario y convierte animaciones breves, dejando constancia de la compatibilidad, la calidad y el tamaño resultantes.

Tema

Revisión de notas de versión para web, Slack y PDF

Revisa una versión frente a su registro de cambios, valida la sintaxis y las referencias de Markdown y prepara notas coherentes para web, Slack y PDF.

Inicio
Herramientas3212
Ejemplos593
Visualizaciones471
Visores de archivos103
Temas239
Etiquetas333
Imágenes, audio y video657

Herramientas de procesamiento, conversión y optimización de imágenes, audio y video

Matemáticas, fechas y finanzas647

Calculadoras, herramientas numéricas, lógica de fechas, estadística y finanzas

Diseño y color298

Herramientas de color, maquetación, gráficos, estilo visual y apoyo al diseño

Texto y redacción209

Herramientas de redacción, limpieza, formato, extracción y análisis de texto

Desarrollo y Web193

Utilidades para desarrolladores, red, depuración web y automatización

Conversión y codificación175

Herramientas de conversión de formatos, archivos, unidades, archivos comprimidos y codificación

Lanzamiento de un cuestionario de captación y entrega de contactos
Textos conmemorativos: revisión familiar y entrega para impresión
Hábitos privados: copia, restauración y revisión antes de compartir
De artículo a borradores de X y LinkedIn: revisión factual y entrega
Revisión de una lección Markdown interactiva y entrega sin conexión

© 2026 Elysia Tools. Todos los derechos reservados.

DocumentaciónPreciosAcerca deTérminos de servicioPolítica de privacidadCookiesContacto

Development

Generador de Cadenas Regex

Genera cadenas aleatorias que coinciden con un patrón de expresión regular

Text Processing

Contiene Cadena

Comprueba si una cadena contiene subcadenas o caracteres específicos

Utilities

Reemplazador de Archivos de Texto

Buscar y reemplazar texto en archivos con soporte para regex, múltiples patrones y creación de respaldos

Format Conversion

Convertidor Hex a Texto

Convierte texto hacia/desde cadenas hexadecimales con espaciado, prefijo (0x/\x/U+) y opciones de mayúsculas/minúsculas flexibles

Generator

Generador de Cadenas Aleatorias

Genera cadenas aleatorias con conjuntos de caracteres, longitud y patrones personalizables

Development

Vista Previa de Reemplazo Regex

Vista previa en tiempo real de reemplazos regex con resaltado de diferencias y estadísticas

Utilities

Buscador de Archivos de Texto

Buscar patrones de texto en archivos con opciones avanzadas (regex, sensible a mayúsculas, palabra completa, etc.)

Text Processing

Filtrar Líneas de Texto

Devolver rápidamente líneas de texto que coincidan con un patrón o una expresión regular

Java

Ejemplos de Procesamiento de Cadenas Android Java

Ejemplos de procesamiento de cadenas Android Java incluyendo división y unión de cadenas, expresiones regulares y reemplazo de cadenas

Kotlin

Ejemplos de Procesamiento de Cadenas Android Kotlin

Ejemplos de procesamiento de cadenas Android Kotlin incluyendo dividir y unir cadenas, expresiones regulares y reemplazo de cadenas

Swift

Ejemplos de Procesamiento de Cadenas macOS Swift

Ejemplos de procesamiento de cadenas macOS Swift incluyendo dividir/unir, expresiones regulares y reemplazo de cadenas

Python

Ejemplos de Procesamiento de Cadenas Web Python

Ejemplos de procesamiento de cadenas Web Python incluyendo división/unión de cadenas, expresiones regulares y reemplazo de cadenas

Objective-C

Procesamiento de Cadenas macOS Objective-C - Ejemplos

Ejemplos de procesamiento de cadenas macOS Objective-C incluyendo NSString, NSMutableString, búsqueda, regex y codificación

Procesamiento de texto

Ejemplos de Reemplazo de Regex

Colección de patrones de reemplazo de regex comunes y útiles para transformación de texto y limpieza de datos