Skip to content

Commit 72618c6

Browse files
tmccombsBurntSushi
authored andcommitted
regex: add Captures::as_match method
To simplify getting the whole match from `Captures` without needing to write `unwrap()`. Fixes #1146, Closes #1227
1 parent 821a8ea commit 72618c6

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

CHANGELOG.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1-
1.11.4 (TBD)
1+
1.12.0 (TBD)
22
============
33
TODO
44

5+
Improvements:
6+
7+
* [FEATURE #1146](https://github.com/rust-lang/regex/issues/1146):
8+
Add `Capture::get_match` for returning the overall match without `unwrap()`.
9+
510
Bug fixes:
611

712
* [BUG #1116](https://github.com/rust-lang/regex/issues/1116):

src/regex/bytes.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1665,6 +1665,26 @@ impl<'h> Captures<'h> {
16651665
.map(|sp| Match::new(self.haystack, sp.start, sp.end))
16661666
}
16671667

1668+
/// Return the overall match for the capture.
1669+
///
1670+
/// This returns the match for index `0`. That is it is equivalent to
1671+
/// `m.get(0).unwrap()`
1672+
///
1673+
/// # Example
1674+
///
1675+
/// ```
1676+
/// use regex::bytes::Regex;
1677+
///
1678+
/// let re = Regex::new(r"[a-z]+([0-9]+)").unwrap();
1679+
/// let caps = re.captures(b" abc123-def").unwrap();
1680+
///
1681+
/// assert_eq!(caps.get_match().as_bytes(), b"abc123");
1682+
/// ```
1683+
#[inline]
1684+
pub fn get_match(&self) -> Match {
1685+
self.get(0).unwrap()
1686+
}
1687+
16681688
/// Returns the `Match` associated with the capture group named `name`. If
16691689
/// `name` isn't a valid capture group or it refers to a group that didn't
16701690
/// match, then `None` is returned.

src/regex/string.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1675,6 +1675,27 @@ impl<'h> Captures<'h> {
16751675
.map(|sp| Match::new(self.haystack, sp.start, sp.end))
16761676
}
16771677

1678+
/// Return the overall match for the capture.
1679+
///
1680+
/// This returns the match for index `0`. That is it is equivalent to
1681+
/// `m.get(0).unwrap()`
1682+
///
1683+
/// # Example
1684+
///
1685+
/// ```
1686+
/// use regex::Regex;
1687+
///
1688+
/// let re = Regex::new(r"[a-z]+([0-9]+)").unwrap();
1689+
/// let caps = re.captures(" abc123-def").unwrap();
1690+
///
1691+
/// assert_eq!(caps.get_match().as_str(), "abc123");
1692+
///
1693+
/// ```
1694+
#[inline]
1695+
pub fn get_match(&self) -> Match {
1696+
self.get(0).unwrap()
1697+
}
1698+
16781699
/// Returns the `Match` associated with the capture group named `name`. If
16791700
/// `name` isn't a valid capture group or it refers to a group that didn't
16801701
/// match, then `None` is returned.

0 commit comments

Comments
 (0)