Reguläre Ausdrücke in Rust: Vollständiger Leitfaden mit Beispielen

Online Python-Trainer für Anfänger

Lernen Sie Python einfach ohne theoretische Überlastung. Lösen Sie praktische Aufgaben mit automatischer Überprüfung und schreiben Sie Code direkt im Browser.

Kurs starten
lace(email, "$1(at)$2"); println!("{}", replaced); // "user(at)example.com" }

Advanced Features and Optimization

The regex crate supports many advanced features. Here are some of them:

use regex::RegexBuilder;  
use regex::Regex;  

fn main() {  
    // Case-insensitive matching  
    let re = RegexBuilder::new(r"rust")  
        .case_insensitive(true)  
        .build()  
        .unwrap();  
    assert!(re.is_match("I love RUST!"));  

    // Multiline mode (^ and $ match line boundaries)  
    let re = Regex::new(r"(?m)^\\d+").unwrap();  
    let text = "123 first line\n456 second line\n789 third line";  
    for mat in re.find_iter(text) {  
        println!("Found number at start of line: {}", mat.as_str());  
    }  

    // Non-greedy matching  
    let re = Regex::new(r"<.*?>").unwrap();  
    let html = "<p>text</p><span>more</span>";  
    for mat in re.find_iter(html) {  
        println!("Tag: {}", mat.as_str());  
    }  

    // Optimization: compile regex once and reuse  
    let re = Regex::new(r"pattern").unwrap();  
    // Reuse `re` multiple times in a loop or function  
}


Error Handling

When creating a regular expression, it's important to handle potential errors correctly:

use regex::Regex;  

fn main() {  
    // Creating a regex with possible error  
    let pattern = r"[invalid"; // intentionally broken pattern  
    match Regex::new(pattern) {  
        Ok(re) => {  
            println!("Regex created successfully");  
            if re.is_match("test") {  
                println!("Pattern matched");  
            }  
        }  
        Err(e) => {  
            eprintln!("Error creating regex: {}", e);  
            // Handle the error: use a default pattern,  
            // try an alternative, or log the error  
        }  
    }  

    // Using Regex::new with unwrap only if pattern is guaranteed valid  
    let safe_re = Regex::new(r"\\d+").unwrap();  
    // ... use safe_re  
}


Performance Considerations

When working with regex in Rust, keep the following in mind:

  • Compile regular expressions outside of loops to avoid repeated compilation overhead
  • Use the RegexSet type if you need to check multiple patterns against the same text
  • For simple substring searches, consider using str::contains() instead of regex
  • When using capture groups, remember that each group adds overhead, especially with large texts or complex patterns


Conclusion

The regex crate in Rust provides a powerful and safe way to work with regular expressions. Runtime errors related to regular expressions are minimized thanks to Rust's type system. The crate is actively used in many real-world projects and is regularly updated, offering excellent documentation and community support. Mastering regular expressions in Rust will help you write more efficient text processing code.

Blogs

Buchempfehlungen