-
Notifications
You must be signed in to change notification settings - Fork 483
How do I get all the matches in repeat capture group? #1269
-
use regex::Regex; fn main() { let regex = Regex::new("((?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2}),?)+").unwrap(); for c in regex.captures_iter("2015-01-02,2025年12月24日") { println!("{c:?}"); for m in c.iter() { println!("{m:?}"); } } }
I'd expect to go over both "2015-01-02" and "2025-12-24", but it seems only the last group retains:
Captures({0: 0..22/"2015-01-02,2025年12月24日,", 1: 11..22/"2025-12-24,", 2/"year": 11..15/"2025", 3/"month": 16..18/"12", 4/"day": 19..21/"24"})
Some(Match { start: 0, end: 22, string: "2015-01-02,2025年12月24日," })
Some(Match { start: 11, end: 22, string: "2025-12-24," })
Some(Match { start: 11, end: 15, string: "2025" })
Some(Match { start: 16, end: 18, string: "12" })
Some(Match { start: 19, end: 21, string: "24" })
Beta Was this translation helpful? Give feedback.
All reactions
You can't. I'm not sure why you would expect that. Most regex engines don't let you access repeated matches of a capture group within one single overall match. The regex crate does not allow it. It doesn't track the state necessary for such a thing.
You need to change your regex pattern or use additional regexes.
Replies: 2 comments
-
You can't. I'm not sure why you would expect that. Most regex engines don't let you access repeated matches of a capture group within one single overall match. The regex crate does not allow it. It doesn't track the state necessary for such a thing.
You need to change your regex pattern or use additional regexes.
Beta Was this translation helpful? Give feedback.
All reactions
-
use regex::Regex; fn main() { let regex = Regex::new("((?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2}),?)+").unwrap(); for c in regex.captures_iter("2015-01-02,2025年12月24日") { println!("{c:?}"); for m in c.iter() { println!("{m:?}"); } } }I'd expect to go over both "2015-01-02" and "2025-12-24", but it seems only the last group retains:
Captures({0: 0..22/"2015-01-02,2025年12月24日,", 1: 11..22/"2025-12-24,", 2/"year": 11..15/"2025", 3/"month": 16..18/"12", 4/"day": 19..21/"24"}) Some(Match { start: 0, end: 22, string: "2015-01-02,2025年12月24日," }) Some(Match { start: 11, end: 22, string: "2025-12-24," }) Some(Match { start: 11, end: 15, string: "2025" }) Some(Match { start: 16, end: 18, string: "12" }) Some(Match { start: 19, end: 21, string: "24" })
Well do you mean you need an output matches of 2015年01月02日 & 2025年12月24日, in that case, your regex pattern is wrong, as it matches all the continuous data matches because of + operator (repetition specifier.)
Beta Was this translation helpful? Give feedback.