rustHow to use named capture groups in Rust regex?
Named capture groups in Rust regex are used to capture a part of a string and assign it a name. This allows for easier access to the captured part of the string.
Example code
let re = Regex::new(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})").unwrap();
let caps = re.captures("2020-04-30").unwrap();
println!("Year: {}", caps.name("year").unwrap());
println!("Month: {}", caps.name("month").unwrap());
println!("Day: {}", caps.name("day").unwrap());
Output example
Year: 2020
Month: 04
Day: 30
Code explanation
let re = Regex::new(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})").unwrap();
: This line creates a new Regex object with the pattern(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})
. The?P<year>
and?P<month>
and?P<day>
are the named capture groups.let caps = re.captures("2020-04-30").unwrap();
: This line captures the string2020-04-30
using the Regex objectre
.println!("Year: {}", caps.name("year").unwrap());
: This line prints the value of the capture groupyear
which is2020
.
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 replace strings using Rust regex?
- How to get a capture group using Rust regex?
- How to parse a file with 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?
More of Rust
- How to replace strings using Rust regex?
- How to use regex to match a group in Rust?
- How to use regex to match a double quote in Rust?
- How to parse JSON string in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to use non-capturing groups in Rust regex?
- How to get a capture group using Rust regex?
- How to perform matrix operations in Rust?
- How to get an entry from a HashSet in Rust?
See more codes...