Reputation: 445
I only find one way is that using a Captures iter to check which index is Some(..).
let re = Regex::new(r"([a-zA-Z_][a-zA-Z0-9]*)|([0-9]+)|(\.)|(=)").unwrap();
for cap in re.captures_iter("asdf.aeg = 34") {
let mut index = 0;
for (i, name) in cap.iter().enumerate() {
if i == 0 {continue}
if let Some(_) = name {index = i; break;}
}
println!("group {:?}, match {:?}", index, cap.at(index).unwrap());
}
Is there a proper way?
Upvotes: 2
Views: 2963
Reputation: 128011
I think your code is almost as close as you can get. Here is a slightly more idiomatic version:
let re = Regex::new(r"([a-zA-Z_][a-zA-Z0-9]*)|([0-9]+)|(\.)|(=)").unwrap();
for cap in re.captures_iter("asdf.aeg = 34") {
let index = cap.iter().enumerate()
.skip(1) // skip the first group
.find(|t| t.1.is_some()) // find the first `Some`
.map(|t| t.0) // extract the index
.unwrap_or(0); // get the index
println!("group {:?}, match {:?}", index, cap.get(index).unwrap().as_str());
}
Upvotes: 3