Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

Rust

Web Rust 字符串处理示例

Web Rust 字符串处理示例,包括字符串分割连接、正则表达式和替换操作

案例

这个案例集合中的条目

代码rust简单

字符串分割/连接

按分隔符分割字符串并使用连接符合并字符串集合

难度

3/10

预计时间

15 min

标签

rust, web, string processing

前置条件

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 ===");
}
代码rust中等

正则表达式

在Rust中使用正则表达式进行模式匹配和文本搜索

难度

6/10

预计时间

25 min

标签

rust, web, string processing, regex

前置条件

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(())
}
代码rust中等

字符串替换

使用各种模式和策略查找并替换子字符串

难度

5/10

预计时间

20 min

标签

rust, web, string processing

前置条件

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

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

音频处理回归测试:空差、失真复核与报告交接

固定参考音频并与另行处理的结果比较,记录空差覆盖范围和适用单音的 THD,连同原文件、残差、复核结论及哈希交付回归证据。

专题

获授权 Webhook 捕获与接收端信任检查

在获授权的测试环境捕获并回放受控 Webhook 请求,分别检查投递证据和接收端 HTTPS 证书,不把证书有效误写成业务信任证明。

专题

用日志、链路、Webhook 和 JSON 载荷做可观测性调试

解析日志,解码调用链,检查 Webhook/API 证据,探索 JSON 载荷,并提取重复模式,形成可用于事故复盘的调试结论。

专题

视频容器转换与转码质量控制

在 MP4、AVI、FLV、MKV、MOV、WebM 之间转换视频容器,用 CRF 和码率参数掌控重编码质量,并以一套留档配置批量处理整个视频库。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Development

正则逆向生成器

根据正则表达式随机生成匹配的测试字符串

Text Processing

字符串包含检测

检查字符串是否包含指定的子字符串或字符

Utilities

文本文件替换器

在文件中查找并替换文本,支持正则表达式、多重模式和备份创建

Format Conversion

十六进制字符串转换器

在文本与十六进制字符串之间互转,支持灵活分隔、前缀(0x/\x/U+)与大小写选项

Generator

随机字符串生成器

生成具有可自定义字符集、长度和模式的随机字符串

Development

正则替换预览器

实时预览正则替换,显示详细差异和统计

Utilities

文本文件搜索器

在文件中搜索文本模式,支持高级选项(正则表达式、区分大小写、全字匹配等)

Text Processing

过滤文本行

快速返回匹配模式或正则表达式的文本行

Java

Android Java 字符串处理示例

Android Java 字符串处理示例,包括字符串分割连接、正则表达式和字符串替换

Kotlin

Android Kotlin 字符串处理示例

Android Kotlin 字符串处理示例,包括字符串分割连接、正则表达式和字符串替换

Swift

macOS Swift 字符串处理示例

macOS Swift 字符串处理示例,包括分割/连接、正则表达式和字符串替换

Python

Web Python 字符串处理示例

Web Python 字符串处理示例,包括字符串分割连接、正则表达式和字符串替换

Objective-C

macOS Objective-C 字符串处理示例

macOS Objective-C 字符串处理示例,包括NSString、NSMutableString、搜索、正则表达式和编码

文本处理

正则替换示例

用于文本转换和数据清洗的常用正则替换模式集合