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 newRegex
object 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 theRegex
object.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 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 match a URL with a regex in Rust?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- How to get a capture group using Rust regex?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
More of Rust
- How to use regex to match a double quote in Rust?
- How to replace all matches using Rust regex?
- How to split a string with Rust regex?
- How to get struct value in Rust
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to get a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use groups in a Rust regex?
See more codes...