diff --git a/src/re_bytes.rs b/src/re_bytes.rs index 2e38c10ca8..347fc1dd70 100644 --- a/src/re_bytes.rs +++ b/src/re_bytes.rs @@ -1,7 +1,7 @@ use std::borrow::Cow; use std::collections::HashMap; use std::fmt; -use std::ops::Index; +use std::ops::{Index, Range}; use std::str::FromStr; use std::sync::Arc; @@ -36,10 +36,17 @@ impl<'t> Match<'t> { self.end } + /// Returns the range over the starting and ending byte offsets of the match + /// in the haystack. + #[inline] + pub fn range(&self) -> Range { + self.start..self.end + } + /// Returns the matched text. #[inline] pub fn as_bytes(&self) -> &'t [u8] { - &self.text[self.start..self.end] + &self.text[self.range()] } /// Creates a new match from the given haystack and byte offsets. @@ -49,6 +56,12 @@ impl<'t> Match<'t> { } } +impl<'t> From> for Range { + fn from(m: Match<'t>) -> Range { + m.range() + } +} + /// A compiled regular expression for matching arbitrary bytes. /// /// It can be used to search, split or replace text. All searching is done with diff --git a/src/re_unicode.rs b/src/re_unicode.rs index 81aac15260..eba00822f4 100644 --- a/src/re_unicode.rs +++ b/src/re_unicode.rs @@ -1,7 +1,7 @@ use std::borrow::Cow; use std::collections::HashMap; use std::fmt; -use std::ops::Index; +use std::ops::{Index, Range}; use std::str::FromStr; use std::sync::Arc; @@ -45,10 +45,17 @@ impl<'t> Match<'t> { self.end } + /// Returns the range over the starting and ending byte offsets of the match + /// in the haystack. + #[inline] + pub fn range(&self) -> Range { + self.start..self.end + } + /// Returns the matched text. #[inline] pub fn as_str(&self) -> &'t str { - &self.text[self.start..self.end] + &self.text[self.range()] } /// Creates a new match from the given haystack and byte offsets. @@ -64,6 +71,12 @@ impl<'t> From> for &'t str { } } +impl<'t> From> for Range { + fn from(m: Match<'t>) -> Range { + m.range() + } +} + /// A compiled regular expression for matching Unicode strings. /// /// It is represented as either a sequence of bytecode instructions (dynamic)