expression

Optional capture groups

An optional group may be absent even though the entire expression matched. Use get rather than indexing an optional capture. This example uses the external regex crate; see the staged Cargo manifest. Expected stdout (not executed): None Some("7") Common mistake: Indexing an optional capture and panicking when absent.

Formal Syntax & Structure

rust syntaxrust
captures.get(index) -> Option<Match>

Working Example

Example Snippetrust
fn main() {    let re = regex::Regex::new(r"item(?:-([0-9]+))?").unwrap();    for text in ["item", "item-7"] {        let c = re.captures(text).unwrap();        println!("{:?}", c.get(1).map(|m| m.as_str()));    }}
Rust Reference