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 a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to match whitespace with a regex in Rust?
- How to use Unicode in a regex in Rust?
- How to replace strings using Rust regex?
- How to get a capture group using Rust regex?
- How to parse a file with Rust regex?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
- Regex example to match multiline string in Rust?
More of Rust
- How to use look behind in regex in Rust?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
- How to use regex captures in Rust?
- Word boundary example in regex in Rust
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to use negation in Rust regex?
See more codes...