rustHow to use regex captures in Rust?
Regex captures in Rust are used to capture substrings from a given string. Captures are stored in a Vec and can be accessed by index.
Example code
let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
let text = "Today is 2020-07-30";
let captures = re.captures(text).unwrap();
println!("Year: {}", &captures[1]);
println!("Month: {}", &captures[2]);
println!("Day: {}", &captures[3]);
Output example
Year: 2020
Month: 07
Day: 30
Code explanation
let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();: This line creates a newRegexobject with the given pattern. The pattern(\d{4})-(\d{2})-(\d{2})matches a date in the formatYYYY-MM-DD.let text = "Today is 2020-07-30";: This line creates a string with the date to be matched.let captures = re.captures(text).unwrap();: This line captures the substrings from the given string using theRegexobject.println!("Year: {}", &captures[1]);: This line prints the first capture, which is the year.println!("Month: {}", &captures[2]);: This line prints the second capture, which is the month.println!("Day: {}", &captures[3]);: This line prints the third capture, which is the day.
Helpful links
Related
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using 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?
- How to use regex lookbehind in Rust?
- How to parse a file with Rust regex?
- How to use regex lookahead in Rust?
- How to match the end of a line in a Rust regex?
More of Rust
- Regex example to match multiline string in Rust?
- How to replace a capture group using Rust regex?
- How to match digits with regex in Rust?
- How to use regex to match a double quote in Rust?
- How to convert the keys of a Rust HashMap to a vector?
- Yield example in Rust
- How to insert an element into a Rust HashMap if it does not already exist?
- Generator example in Rust
- How to match the end of a line in a Rust regex?
- How to replace all matches using Rust regex?
See more codes...