Using Rust's crate regex, how to get the position for a group?

Viewed 642

Please let me know how to get the position for a matched group, using Rust's crate regex.

I found how to match a regular expression against a text as follows.

extern crate regex;
use regex::Regex;

fn main() {
    let str = "ABC 01 D2E";

    let re = Regex::new(r"(\s)(\d+)(\s)").unwrap();
    let caps = re.captures(str).unwrap();
    println!("{}", caps.get(2).unwrap().as_str()); // I expect "01" on stdout.
}

Though, I still don't know (how to get) where "01" is on the text. That is, the index of "0" on "ABC 01 D2E".

1 Answers

Captures::get returns an Option<Match>>, so you can use Match::start to get the starting index:

println!("{}", caps.get(2).unwrap().start());
// prints 4
Related