expression

Raw strings for regex patterns

Rust string syntax and regular-expression syntax are separate layers. A raw string preserves the backslash so the regex engine can interpret it. This example uses the external regex crate; see the staged Cargo manifest. Expected stdout (not executed): true true Common mistake: Writing an invalid Rust string escape when intending a regex escape.

Formal Syntax & Structure

rust syntaxrust
r"\d+" versus "\\d+"

Working Example

Example Snippetrust
fn main() {    let a = regex::Regex::new(r"\d+").unwrap();    let b = regex::Regex::new("\\d+").unwrap();    println!("{} {}", a.is_match("9"), b.is_match("9"));}
Rust Reference