pub struct Regex(/* private fields */);
Expand description
A compiled regular expression.
Implementations§
Source§impl Regex
impl Regex
Sourcepub fn new(re: &str) -> Result<Regex>
pub fn new(re: &str) -> Result<Regex>
Parse and compile a regex with default options, see RegexBuilder
.
Returns an Error
if the pattern could not be parsed.
Sourcepub fn is_match(&self, text: &str) -> Result<bool>
pub fn is_match(&self, text: &str) -> Result<bool>
Check if the regex matches the input text.
§Example
Test if some text contains the same word twice:
let re = Regex::new(r"(\w+) \1").unwrap();
assert!(re.is_match("mirror mirror on the wall").unwrap());
Sourcepub fn find<'t>(&self, text: &'t str) -> Result<Option<Match<'t>>>
pub fn find<'t>(&self, text: &'t str) -> Result<Option<Match<'t>>>
Find the first match in the input text.
If you have capturing groups in your regex that you want to extract, use the [captures()] method.
§Example
Find a word that is followed by an exclamation point:
let re = Regex::new(r"\w+(?=!)").unwrap();
assert_eq!(re.find("so fancy!").unwrap().unwrap().as_str(), "fancy");
Sourcepub fn captures<'t>(&self, text: &'t str) -> Result<Option<Captures<'t>>>
pub fn captures<'t>(&self, text: &'t str) -> Result<Option<Captures<'t>>>
Returns the capture groups for the first match in text
.
If no match is found, then Ok(None)
is returned.
§Examples
Finding matches and capturing parts of the match:
let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
let text = "The date was 2018-04-07";
let captures = re.captures(text).unwrap().unwrap();
assert_eq!(captures.get(1).unwrap().as_str(), "2018");
assert_eq!(captures.get(2).unwrap().as_str(), "04");
assert_eq!(captures.get(3).unwrap().as_str(), "07");
assert_eq!(captures.get(0).unwrap().as_str(), "2018-04-07");
Sourcepub fn captures_from_pos<'t>(
&self,
text: &'t str,
pos: usize,
) -> Result<Option<Captures<'t>>>
pub fn captures_from_pos<'t>( &self, text: &'t str, pos: usize, ) -> Result<Option<Captures<'t>>>
Returns the capture groups for the first match in text
, starting from
the specified byte position pos
.
§Examples
Finding captures starting at a position:
let re = Regex::new(r"(?m:^)(\d+)").unwrap();
let text = "1 test 123\n2 foo";
let captures = re.captures_from_pos(text, 7).unwrap().unwrap();
let group = captures.get(1).unwrap();
assert_eq!(group.as_str(), "2");
assert_eq!(group.start(), 11);
assert_eq!(group.end(), 12);
Note that in some cases this is not the same as using the captures
methods and passing a slice of the string, see the capture that we get
when we do this:
let re = Regex::new(r"(?m:^)(\d+)").unwrap();
let text = "1 test 123\n2 foo";
let captures = re.captures(&text[7..]).unwrap().unwrap();
assert_eq!(captures.get(1).unwrap().as_str(), "123");
This matched the number “123” because it’s at the beginning of the text of the string slice.