rustHow to use captures_iter with regex in Rust?
Using captures_iter with regex in Rust is a powerful way to extract data from strings. captures_iter returns an iterator of all the captures that match a given pattern.
Example code
let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
let text = "Today is 2020-04-30";
for cap in re.captures_iter(text) {
println!("Year: {}, Month: {}, Day: {}", &cap[1], &cap[2], &cap[3]);
}
Output example
Year: 2020, Month: 04, Day: 30
Code explanation
Regex::new(r"(\d{4})-(\d{2})-(\d{2})"): creates a new Regex object with the given pattern.captures_iter: returns an iterator of all the captures that match the given pattern.&cap[1], &cap[2], &cap[3]: accesses the captures from the iterator.
Helpful links
Related
- How to replace strings using Rust regex?
- Regex example to match multiline string in Rust?
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use negation in Rust regex?
- How to use regex lookbehind in Rust?
- How to use regex lookahead in Rust?
- How to ignore case in Rust regex?
More of Rust
- How to convert a Rust slice of u8 to u32?
- How to split a Rust slice?
- How to match a URL with a regex in Rust?
- Regex example to match multiline string in Rust?
- How to match the end of a line in a Rust regex?
- How to convert a u8 slice to a hex string in Rust?
- How to replace a capture group using Rust regex?
- How to split a string with Rust regex?
- How to parse a file with Rust regex?
- How to borrow from vector in Rust
See more codes...