Struct Captures
pub struct Captures<'h> { /* private fields */ }
Represents the capture groups for a single match.
Capture groups refer to parts of a regex enclosed in parentheses. They
can be optionally named. The purpose of capture groups is to be able to
reference different parts of a match based on the original pattern. In
essence, a Captures is a container of Match values for each group
that participated in a regex match. Each Match can be looked up by either
its capture group index or name (if it has one).
For example, say you want to match the individual letters in a 5-letter word:
(?<first>\w)(\w)(?:\w)\w(?<last>\w)
This regex has 4 capture groups:
- The group at index
0corresponds to the overall match. It is always present in every match and never has a name. - The group at index
1with namefirstcorresponding to the first letter. - The group at index
2with no name corresponding to the second letter. - The group at index
3with namelastcorresponding to the fifth and last letter.
Notice that (?:\w) was not listed above as a capture group despite it
being enclosed in parentheses. That's because (?:pattern) is a special
syntax that permits grouping but without capturing. The reason for not
treating it as a capture is that tracking and reporting capture groups
requires additional state that may lead to slower searches. So using as few
capture groups as possible can help performance. (Although the difference
in performance of a couple of capture groups is likely immaterial.)
Values with this type are created by Regex::captures or
Regex::captures_iter.
'h is the lifetime of the haystack that these captures were matched from.
Example
use Regex;
let re = new.unwrap;
let caps = re.captures.unwrap;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Implementations
impl<'h> Captures<'h>
fn get(&self, i: usize) -> Option<Match<'h>>Returns the
Matchassociated with the capture group at indexi. Ifidoes not correspond to a capture group, or if the capture group did not participate in the match, thenNoneis returned.When
i == 0, this is guaranteed to return a non-Nonevalue.Examples
Get the substring that matched with a default of an empty string if the group didn't participate in the match:
use Regex; let re = new.unwrap; let caps = re.captures.unwrap; let substr1 = caps.get.map_or; let substr2 = caps.get.map_or; assert_eq!; assert_eq!;fn get_match(&self) -> Match<'h>Return the overall match for the capture.
This returns the match for index
0. That is it is equivalent tom.get(0).unwrap()Example
use Regex; let re = new.unwrap; let caps = re.captures.unwrap; assert_eq!;fn name(&self, name: &str) -> Option<Match<'h>>Returns the
Matchassociated with the capture group namedname. Ifnameisn't a valid capture group or it refers to a group that didn't match, thenNoneis returned.Note that unlike
caps["name"], this returns aMatchwhose lifetime matches the lifetime of the haystack in thisCapturesvalue. Conversely, the substring returned bycaps["name"]has a lifetime of theCapturesvalue, which is likely shorter than the lifetime of the haystack. In some cases, it may be necessary to use this method to access the matching substring instead of thecaps["name"]notation.Examples
Get the substring that matched with a default of an empty string if the group didn't participate in the match:
use Regex; let re = new.unwrap; let caps = re.captures.unwrap; let numbers = caps.name.map_or; let letters = caps.name.map_or; assert_eq!; assert_eq!;fn extract<const N: usize>(&self) -> (&'h str, [&'h str; N])This is a convenience routine for extracting the substrings corresponding to matching capture groups.
This returns a tuple where the first element corresponds to the full substring of the haystack that matched the regex. The second element is an array of substrings, with each corresponding to the substring that matched for a particular capture group.
Panics
This panics if the number of possible matching groups in this
Capturesvalue is not fixed toNin all circumstances. More precisely, this routine only works whenNis equivalent toRegex::static_captures_len.Stated more plainly, if the number of matching capture groups in a regex can vary from match to match, then this function always panics.
For example,
(a)(b)|(c)could produce two matching capture groups or one matching capture group for any given match. Therefore, one cannot useextractwith such a pattern.But a pattern like
(a)(b)|(c)(d)can be used withextractbecause the number of capture groups in every match is always equivalent, even if the capture indices in each match are not.Example
use Regex; let re = new.unwrap; let hay = "On 2010-03-14, I became a Tennessee lamb."; let Some = re.captures.map else ; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Example: iteration
This example shows how to use this method when iterating over all
Capturesmatches in a haystack.use Regex; let re = new.unwrap; let hay = "1973-01-05, 1975-08-25 and 1980-10-18"; let mut dates: = vec!; for in re.captures_iter.map assert_eq!;Example: parsing different formats
This API is particularly useful when you need to extract a particular value that might occur in a different format. Consider, for example, an identifier that might be in double quotes or single quotes:
use Regex; let re = new.unwrap; let hay = r#"The first is id:"foo" and the second is id:'bar'."#; let mut ids = vec!; for in re.captures_iter.map assert_eq!;fn expand(&self, replacement: &str, dst: &mut String)Expands all instances of
$refinreplacementto the corresponding capture group, and writes them to thedstbuffer given. Arefcan be a capture group index or a name. Ifrefdoesn't refer to a capture group that participated in the match, then it is replaced with the empty string.Format
The format of the replacement string supports two different kinds of capture references: unbraced and braced.
For the unbraced format, the format supported is
$refwherenamecan be any character in the class[0-9A-Za-z_].refis always the longest possible parse. So for example,$1acorresponds to the capture group named1aand not the capture group at index1. Ifrefmatches^[0-9]+$, then it is treated as a capture group index itself and not a name.For the braced format, the format supported is
${ref}whererefcan be any sequence of bytes except for}. If no closing brace occurs, then it is not considered a capture reference. As with the unbraced format, ifrefmatches^[0-9]+$, then it is treated as a capture group index and not a name.The braced format is useful for exerting precise control over the name of the capture reference. For example,
${1}acorresponds to the capture group reference1followed by the lettera, where as$1a(as mentioned above) corresponds to the capture group reference1a. The braced format is also useful for expressing capture group names that use characters not supported by the unbraced format. For example,${foo[bar].baz}refers to the capture group namedfoo[bar].baz.If a capture group reference is found and it does not refer to a valid capture group, then it will be replaced with the empty string.
To write a literal
$, use$$.Example
use Regex; let re = new.unwrap; let hay = "On 14-03-2010, I became a Tennessee lamb."; let caps = re.captures.unwrap; let mut dst = Stringnew; caps.expand; assert_eq!;fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 'h>Returns an iterator over all capture groups. This includes both matching and non-matching groups.
The iterator always yields at least one matching group: the first group (at index
0) with no name. Subsequent groups are returned in the order of their opening parenthesis in the regex.The elements yielded have type
Option<Match<'h>>, where a non-Nonevalue is present if the capture group matches.Example
use Regex; let re = new.unwrap; let caps = re.captures.unwrap; let mut it = caps.iter; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn len(&self) -> usizeReturns the total number of capture groups. This includes both matching and non-matching groups.
The length returned is always equivalent to the number of elements yielded by
Captures::iter. Consequently, the length is always greater than zero since everyCapturesvalue always includes the match for the entire regex.Example
use Regex; let re = new.unwrap; let caps = re.captures.unwrap; assert_eq!;
Trait Implementations
impl<'h> Debug for Captures<'h>
fn fmt(&self, f: &mut Formatter<'_>) -> Result
impl<'h> Index<usize> for Captures<'h>
type Output = str;fn index<'a>(&'a self, i: usize) -> &'a str
impl<'h, 'n> Index<&'n str> for Captures<'h>
type Output = str;fn index<'a>(&'a self, name: &'n str) -> &'a str
Auto Trait Implementations
impl<'h> Freeze for Captures<'h>
impl<'h> RefUnwindSafe for Captures<'h>
impl<'h> Send for Captures<'h>
impl<'h> Sync for Captures<'h>
impl<'h> Unpin for Captures<'h>
impl<'h> UnsafeUnpin for Captures<'h>
impl<'h> UnwindSafe for Captures<'h>
Blanket Implementations
impl<T> Any for Captures<'h>
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for Captures<'h>
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for Captures<'h>
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> From<T> for Captures<'h>
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into<U> for Captures<'h>
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for Captures<'h>
where
U: Into<T>,
type Error = never;fn try_from(value: U) -> Result<T, never>
impl<T, U> TryInto<U> for Captures<'h>
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>