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 match whitespace with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to split a string with Rust regex?
- Regex example to match multiline string in Rust?
- How to get all matches from a Rust regex?
- How to replace all matches using Rust regex?
- How to get a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
More of Rust
- How to use Unicode in a regex in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to use non-capturing groups in Rust regex?
- How to implement PartialEq for a Rust HashMap?
- How to use regex to match a group in Rust?
- How to use regex to match a double quote in Rust?
- How to get a capture group using Rust regex?
- Hashshet example in Rust
- How to use a tuple as a key in a Rust HashMap?
See more codes...