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 match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to get a capture group using Rust regex?
- How to split a string with Rust regex?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- How to use non-capturing groups in Rust regex?
- Regex example to match multiline string in Rust?
More of Rust
- Hashshet example in Rust
- How to use a tuple as a key in a Rust HashMap?
- How to get a capture group using Rust regex?
- How to split a string with Rust regex?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- How to use regex to match a group in Rust?
- How to parse JSON string in Rust?
- How to get an entry from a HashSet in Rust?
- How to convert a Rust HashMap to a JSON string?
See more codes...