Find out the number of captures with regex

How do I find out how many matches there were?

use regex::Regex;

fn main() 
{
    let msting = "1 2 3 4 5 6 a b c 1 2 2";
    let rx = Regex::new(r".*?([[:digit:]]).*?").unwrap();
    let nom_captures = &rx.captures(&msting).len();
    println!["{:?}", nom_captures ];
}

Playground

This appears to work.

let num_captures = rx.captures_iter(&msting).count();
println!("{:?}", num_captures);

captures returns an Option, so you have to handle the case where there is no capture.

Either unwrap (you're sure there'll be some) or handle that case or use capture_iter.

Thanks, that works.

Playground

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.