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 use regex lookbehind in Rust?
- How to match whitespace with a regex in Rust?
- Regex example to match multiline string in Rust?
- How to replace all matches using Rust regex?
- How to match the end of a line in a Rust regex?
- How to match a URL with a regex in Rust?
- How to use Unicode in a regex in Rust?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
More of Rust
- How to get execution time in Rust
- How to iterate over a Rust slice with an index?
- How to borrow from vector in Rust
- How to match whitespace with a regex in Rust?
- How to find the first match in a Rust regex?
- How to iterate an array with index in Rust
- How to calculate the inverse of a matrix in Rust?
- How to use a BuildHasher in Rust?
- Example box expression in Rust
- How do I create a class variable in Rust?
See more codes...