Rust正则表达式实践
正则表达式是一种强大的文本处理工具。在 Rust 中,我们主要通过 regex crate 来使用正则表达式。让我们通过实际案例来学习。 1. 基础匹配 use regex::Regex; fn main() { // 创建正则表达式对象 let re = Regex::new(r"\d+").unwrap(); // 测试匹配 let text = "The year is 2024"; if re.is_match(text) { println!("Found a number!"); } // 提取匹配内容 if let Some(matched) = re.find(text) { println!("Found number: {}", matched.as_str()); } } 2. 处理重复单词 根据文章中提到的一个常见问题 - 查找重复单词: use regex::Regex; fn remove_duplicate_words(text: &str) -> String { // (\w+) 捕获一个单词,\s+匹配空白字符,\1 回引用前面捕获的单词 let re = Regex::new(r"(\w+)\s+\1").unwrap(); re.replace_all(text, "$1").to_string() } fn main() { let text = "the little cat cat in the hat hat."; let result = remove_duplicate_words(text); println!("Original: {}", text); println!("Fixed: {}", result); } 3. 使用断言优化匹配 use regex::Regex; fn find_word_boundaries() { // \b 表示单词边界 let re = Regex::new(r"\b\w+\b").unwrap(); let text = "hello, world!"; for word in re.find_iter(text) { println!("Found word: {}", word.as_str()); } } 4. 性能优化 使用 lazy_static 预编译正则表达式: ...