Skip to content

Commit 9ae9418

Browse files
committed
Add Captures::get example.
The example shows how to get the matched text of any capture group while defaulting to the empty string if that particular group didn't participate in the match. Fixes #338
1 parent 3a6138b commit 9ae9418

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Diff for: src/re_bytes.rs

+16
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,22 @@ impl<'t> Captures<'t> {
789789
/// Returns the match associated with the capture group at index `i`. If
790790
/// `i` does not correspond to a capture group, or if the capture group
791791
/// did not participate in the match, then `None` is returned.
792+
///
793+
/// # Examples
794+
///
795+
/// Get the text of the match with a default of an empty string if this
796+
/// group didn't participate in the match:
797+
///
798+
/// ```rust
799+
/// # use regex::bytes::Regex;
800+
/// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap();
801+
/// let caps = re.captures(b"abc123").unwrap();
802+
///
803+
/// let text1 = caps.get(1).map_or(&b""[..], |m| m.as_bytes());
804+
/// let text2 = caps.get(2).map_or(&b""[..], |m| m.as_bytes());
805+
/// assert_eq!(text1, &b"123"[..]);
806+
/// assert_eq!(text2, &b""[..]);
807+
/// ```
792808
pub fn get(&self, i: usize) -> Option<Match<'t>> {
793809
self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e))
794810
}

Diff for: src/re_unicode.rs

+16
Original file line numberDiff line numberDiff line change
@@ -934,6 +934,22 @@ impl<'t> Captures<'t> {
934934
/// Returns the match associated with the capture group at index `i`. If
935935
/// `i` does not correspond to a capture group, or if the capture group
936936
/// did not participate in the match, then `None` is returned.
937+
///
938+
/// # Examples
939+
///
940+
/// Get the text of the match with a default of an empty string if this
941+
/// group didn't participate in the match:
942+
///
943+
/// ```rust
944+
/// # use regex::Regex;
945+
/// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap();
946+
/// let caps = re.captures("abc123").unwrap();
947+
///
948+
/// let text1 = caps.get(1).map_or("", |m| m.as_str());
949+
/// let text2 = caps.get(2).map_or("", |m| m.as_str());
950+
/// assert_eq!(text1, "123");
951+
/// assert_eq!(text2, "");
952+
/// ```
937953
pub fn get(&self, i: usize) -> Option<Match<'t>> {
938954
self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e))
939955
}

0 commit comments

Comments
 (0)