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 match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to use Unicode in a regex in Rust?
- How to match the end of a line in a Rust regex?
- How to get a capture group using Rust regex?
- How to match all using regex in Rust?
- How to replace a capture group using Rust regex?
- How to split a string with Rust regex?
- How to create a Rust regex from a string?
- How to find the first match in a Rust regex?
More of Rust
- How to replace strings using Rust regex?
- How to create a new Rust HashMap with values?
- How to match whitespace with a regex in Rust?
- How to yield return in Rust?
- How to use Unicode in a regex in Rust?
- How to split a string with Rust regex?
- How to loop until error in Rust
- How to replace a capture group using Rust regex?
- How to perform matrix operations in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
See more codes...