1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::collections::HashMap;
13 use std::from_str::from_str;
14 use std::str::{MaybeOwned, Owned, Slice};
19 use vm::{CaptureLocs, MatchKind, Exists, Location, Submatches};
21 /// Escapes all regular expression meta characters in `text`.
23 /// The string returned may be safely used as a literal in a regular
25 pub fn quote(text: &str) -> String {
26 let mut quoted = String::with_capacity(text.len());
27 for c in text.chars() {
28 if parse::is_punct(c) {
29 quoted.push_char('\\')
36 /// Tests if the given regular expression matches somewhere in the text given.
38 /// If there was a problem compiling the regular expression, an error is
41 /// To find submatches, split or replace text, you'll need to compile an
44 /// Note that you should prefer the `regex!` macro when possible. For example,
45 /// `regex!("...").is_match("...")`.
46 pub fn is_match(regex: &str, text: &str) -> Result<bool, parse::Error> {
47 Regex::new(regex).map(|r| r.is_match(text))
50 /// A compiled regular expression
52 /// It is represented as either a sequence of bytecode instructions (dynamic)
53 /// or as a specialized Rust function (native). It can be used to search, split
54 /// or replace text. All searching is done with an implicit `.*?` at the
55 /// beginning and end of an expression. To force an expression to match the
56 /// whole string (or a prefix or a suffix), you must use an anchor like `^` or
57 /// `$` (or `\A` and `\z`).
59 /// While this crate will handle Unicode strings (whether in the regular
60 /// expression or in the search text), all positions returned are **byte
61 /// indices**. Every byte index is guaranteed to be at a Unicode code point
64 /// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a
65 /// compiled regular expression and text to search, respectively.
67 /// The only methods that allocate new strings are the string replacement
68 /// methods. All other methods (searching and splitting) return borrowed
69 /// pointers into the string given.
73 /// Find the location of a US phone number:
76 /// # use regex::Regex;
77 /// let re = match Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}") {
79 /// Err(err) => fail!("{}", err),
81 /// assert_eq!(re.find("phone: 111-222-3333"), Some((7, 19)));
84 /// You can also use the `regex!` macro to compile a regular expression when
85 /// you compile your program:
88 /// #![feature(phase)]
89 /// extern crate regex;
90 /// #[phase(syntax)] extern crate regex_macros;
93 /// let re = regex!(r"\d+");
94 /// assert_eq!(re.find("123 abc"), Some((0, 3)));
98 /// Given an incorrect regular expression, `regex!` will cause the Rust
99 /// compiler to produce a compile time error.
100 /// Note that `regex!` will compile the expression to native Rust code, which
101 /// makes it much faster when searching text.
102 /// More details about the `regex!` macro can be found in the `regex` crate
105 #[allow(visible_private_types)]
107 // The representation of `Regex` is exported to support the `regex!`
108 // syntax extension. Do not rely on it.
110 // See the comments for the `program` module in `lib.rs` for a more
111 // detailed explanation for what `regex!` requires.
122 names: Vec<Option<String>>,
130 pub original: &'static str,
132 pub names: &'static [Option<&'static str>],
134 pub prog: fn(MatchKind, &str, uint, uint) -> Vec<Option<uint>>
137 impl Clone for Native {
138 fn clone(&self) -> Native { *self }
141 impl fmt::Show for Regex {
142 /// Shows the original regular expression.
143 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
144 write!(f, "{}", self.as_str())
149 /// Compiles a dynamic regular expression. Once compiled, it can be
150 /// used repeatedly to search, split or replace text in a string.
152 /// When possible, you should prefer the `regex!` macro since it is
153 /// safer and always faster.
155 /// If an invalid expression is given, then an error is returned.
156 pub fn new(re: &str) -> Result<Regex, parse::Error> {
157 let ast = try!(parse::parse(re));
158 let (prog, names) = Program::new(ast);
160 original: re.to_string(),
166 /// Returns true if and only if the regex matches the string given.
170 /// Test if some text contains at least one word with exactly 13
174 /// # #![feature(phase)]
175 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
177 /// let text = "I categorically deny having triskaidekaphobia.";
178 /// let matched = regex!(r"\b\w{13}\b").is_match(text);
179 /// assert!(matched);
182 pub fn is_match(&self, text: &str) -> bool {
183 has_match(&exec(self, Exists, text))
186 /// Returns the start and end byte range of the leftmost-first match in
187 /// `text`. If no match exists, then `None` is returned.
189 /// Note that this should only be used if you want to discover the position
190 /// of the match. Testing the existence of a match is faster if you use
195 /// Find the start and end location of the first word with exactly 13
199 /// # #![feature(phase)]
200 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
202 /// let text = "I categorically deny having triskaidekaphobia.";
203 /// let pos = regex!(r"\b\w{13}\b").find(text);
204 /// assert_eq!(pos, Some((2, 15)));
207 pub fn find(&self, text: &str) -> Option<(uint, uint)> {
208 let caps = exec(self, Location, text);
209 if has_match(&caps) {
210 Some((caps.get(0).unwrap(), caps.get(1).unwrap()))
216 /// Returns an iterator for each successive non-overlapping match in
217 /// `text`, returning the start and end byte indices with respect to
222 /// Find the start and end location of every word with exactly 13
226 /// # #![feature(phase)]
227 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
229 /// let text = "Retroactively relinquishing remunerations is reprehensible.";
230 /// for pos in regex!(r"\b\w{13}\b").find_iter(text) {
231 /// println!("{}", pos);
240 pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindMatches<'r, 't> {
249 /// Returns the capture groups corresponding to the leftmost-first
250 /// match in `text`. Capture group `0` always corresponds to the entire
251 /// match. If no match is found, then `None` is returned.
253 /// You should only use `captures` if you need access to submatches.
254 /// Otherwise, `find` is faster for discovering the location of the overall
259 /// Say you have some text with movie names and their release years,
260 /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text
261 /// looking like that, while also extracting the movie name and its release
265 /// # #![feature(phase)]
266 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
268 /// let re = regex!(r"'([^']+)'\s+\((\d{4})\)");
269 /// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
270 /// let caps = re.captures(text).unwrap();
271 /// assert_eq!(caps.at(1), "Citizen Kane");
272 /// assert_eq!(caps.at(2), "1941");
273 /// assert_eq!(caps.at(0), "'Citizen Kane' (1941)");
277 /// Note that the full match is at capture group `0`. Each subsequent
278 /// capture group is indexed by the order of its opening `(`.
280 /// We can make this example a bit clearer by using *named* capture groups:
283 /// # #![feature(phase)]
284 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
286 /// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)");
287 /// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
288 /// let caps = re.captures(text).unwrap();
289 /// assert_eq!(caps.name("title"), "Citizen Kane");
290 /// assert_eq!(caps.name("year"), "1941");
291 /// assert_eq!(caps.at(0), "'Citizen Kane' (1941)");
295 /// Here we name the capture groups, which we can access with the `name`
296 /// method. Note that the named capture groups are still accessible with
299 /// The `0`th capture group is always unnamed, so it must always be
300 /// accessed with `at(0)`.
301 pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> {
302 let caps = exec(self, Submatches, text);
303 Captures::new(self, text, caps)
306 /// Returns an iterator over all the non-overlapping capture groups matched
307 /// in `text`. This is operationally the same as `find_iter` (except it
308 /// yields information about submatches).
312 /// We can use this to find all movie titles and their release years in
313 /// some text, where the movie is formatted like "'Title' (xxxx)":
316 /// # #![feature(phase)]
317 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
319 /// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)");
320 /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931).";
321 /// for caps in re.captures_iter(text) {
322 /// println!("Movie: {}, Released: {}", caps.name("title"), caps.name("year"));
325 /// // Movie: Citizen Kane, Released: 1941
326 /// // Movie: The Wizard of Oz, Released: 1939
327 /// // Movie: M, Released: 1931
330 pub fn captures_iter<'r, 't>(&'r self, text: &'t str)
331 -> FindCaptures<'r, 't> {
340 /// Returns an iterator of substrings of `text` delimited by a match
341 /// of the regular expression.
342 /// Namely, each element of the iterator corresponds to text that *isn't*
343 /// matched by the regular expression.
345 /// This method will *not* copy the text given.
349 /// To split a string delimited by arbitrary amounts of spaces or tabs:
352 /// # #![feature(phase)]
353 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
355 /// let re = regex!(r"[ \t]+");
356 /// let fields: Vec<&str> = re.split("a b \t c\td e").collect();
357 /// assert_eq!(fields, vec!("a", "b", "c", "d", "e"));
360 pub fn split<'r, 't>(&'r self, text: &'t str) -> RegexSplits<'r, 't> {
362 finder: self.find_iter(text),
367 /// Returns an iterator of at most `limit` substrings of `text` delimited
368 /// by a match of the regular expression. (A `limit` of `0` will return no
370 /// Namely, each element of the iterator corresponds to text that *isn't*
371 /// matched by the regular expression.
372 /// The remainder of the string that is not split will be the last element
375 /// This method will *not* copy the text given.
379 /// Get the first two words in some text:
382 /// # #![feature(phase)]
383 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
385 /// let re = regex!(r"\W+");
386 /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect();
387 /// assert_eq!(fields, vec!("Hey", "How", "are you?"));
390 pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: uint)
391 -> RegexSplitsN<'r, 't> {
393 splits: self.split(text),
399 /// Replaces the leftmost-first match with the replacement provided.
400 /// The replacement can be a regular string (where `$N` and `$name` are
401 /// expanded to match capture groups) or a function that takes the matches'
402 /// `Captures` and returns the replaced string.
404 /// If no match is found, then a copy of the string is returned unchanged.
408 /// Note that this function is polymorphic with respect to the replacement.
409 /// In typical usage, this can just be a normal string:
412 /// # #![feature(phase)]
413 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
415 /// let re = regex!("[^01]+");
416 /// assert_eq!(re.replace("1078910", "").as_slice(), "1010");
420 /// But anything satisfying the `Replacer` trait will work. For example,
421 /// a closure of type `|&Captures| -> String` provides direct access to the
422 /// captures corresponding to a match. This allows one to access
423 /// submatches easily:
426 /// # #![feature(phase)]
427 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
428 /// # use regex::Captures; fn main() {
429 /// let re = regex!(r"([^,\s]+),\s+(\S+)");
430 /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| {
431 /// format!("{} {}", caps.at(2), caps.at(1))
433 /// assert_eq!(result.as_slice(), "Bruce Springsteen");
437 /// But this is a bit cumbersome to use all the time. Instead, a simple
438 /// syntax is supported that expands `$name` into the corresponding capture
439 /// group. Here's the last example, but using this expansion technique
440 /// with named capture groups:
443 /// # #![feature(phase)]
444 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
446 /// let re = regex!(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)");
447 /// let result = re.replace("Springsteen, Bruce", "$first $last");
448 /// assert_eq!(result.as_slice(), "Bruce Springsteen");
452 /// Note that using `$2` instead of `$first` or `$1` instead of `$last`
453 /// would produce the same result. To write a literal `$` use `$$`.
455 /// Finally, sometimes you just want to replace a literal string with no
456 /// submatch expansion. This can be done by wrapping a string with
460 /// # #![feature(phase)]
461 /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
463 /// use regex::NoExpand;
465 /// let re = regex!(r"(?P<last>[^,\s]+),\s+(\S+)");
466 /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last"));
467 /// assert_eq!(result.as_slice(), "$2 $last");
470 pub fn replace<R: Replacer>(&self, text: &str, rep: R) -> String {
471 self.replacen(text, 1, rep)
474 /// Replaces all non-overlapping matches in `text` with the
475 /// replacement provided. This is the same as calling `replacen` with
476 /// `limit` set to `0`.
478 /// See the documentation for `replace` for details on how to access
479 /// submatches in the replacement string.
480 pub fn replace_all<R: Replacer>(&self, text: &str, rep: R) -> String {
481 self.replacen(text, 0, rep)
484 /// Replaces at most `limit` non-overlapping matches in `text` with the
485 /// replacement provided. If `limit` is 0, then all non-overlapping matches
488 /// See the documentation for `replace` for details on how to access
489 /// submatches in the replacement string.
490 pub fn replacen<R: Replacer>
491 (&self, text: &str, limit: uint, mut rep: R) -> String {
492 let mut new = String::with_capacity(text.len());
493 let mut last_match = 0u;
495 for (i, cap) in self.captures_iter(text).enumerate() {
496 // It'd be nicer to use the 'take' iterator instead, but it seemed
497 // awkward given that '0' => no limit.
498 if limit > 0 && i >= limit {
502 let (s, e) = cap.pos(0).unwrap(); // captures only reports matches
503 new.push_str(text.slice(last_match, s));
504 new.push_str(rep.reg_replace(&cap).as_slice());
507 new.append(text.slice(last_match, text.len()))
510 /// Returns the original string of this regex.
511 pub fn as_str<'a>(&'a self) -> &'a str {
513 Dynamic(Dynamic { ref original, .. }) => original.as_slice(),
514 Native(Native { ref original, .. }) => original.as_slice(),
519 #[allow(visible_private_types)]
521 pub fn names_iter<'a>(&'a self) -> NamesIter<'a> {
523 Native(ref n) => NamesIterNative(n.names.iter()),
524 Dynamic(ref d) => NamesIterDynamic(d.names.iter())
528 fn names_len(&self) -> uint {
530 Native(ref n) => n.names.len(),
531 Dynamic(ref d) => d.names.len()
538 NamesIterNative(::std::slice::Items<'a, Option<&'static str>>),
539 NamesIterDynamic(::std::slice::Items<'a, Option<String>>)
542 impl<'a> Iterator<Option<String>> for NamesIter<'a> {
543 fn next(&mut self) -> Option<Option<String>> {
545 NamesIterNative(ref mut i) => i.next().map(|x| x.map(|s| s.to_string())),
546 NamesIterDynamic(ref mut i) => i.next().map(|x| x.as_ref().map(|s| s.to_string())),
551 /// NoExpand indicates literal string replacement.
553 /// It can be used with `replace` and `replace_all` to do a literal
554 /// string replacement without expanding `$name` to their corresponding
557 /// `'r` is the lifetime of the literal text.
558 pub struct NoExpand<'t>(pub &'t str);
560 /// Replacer describes types that can be used to replace matches in a string.
562 /// Returns a possibly owned string that is used to replace the match
563 /// corresponding the the `caps` capture group.
565 /// The `'a` lifetime refers to the lifetime of a borrowed string when
566 /// a new owned string isn't needed (e.g., for `NoExpand`).
567 fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a>;
570 impl<'t> Replacer for NoExpand<'t> {
571 fn reg_replace<'a>(&'a mut self, _: &Captures) -> MaybeOwned<'a> {
572 let NoExpand(s) = *self;
577 impl<'t> Replacer for &'t str {
578 fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a> {
579 Owned(caps.expand(*self))
583 impl<'t> Replacer for |&Captures|: 't -> String {
584 fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a> {
589 /// Yields all substrings delimited by a regular expression match.
591 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
592 /// of the string being split.
593 pub struct RegexSplits<'r, 't> {
594 finder: FindMatches<'r, 't>,
598 impl<'r, 't> Iterator<&'t str> for RegexSplits<'r, 't> {
599 fn next(&mut self) -> Option<&'t str> {
600 let text = self.finder.search;
601 match self.finder.next() {
603 if self.last >= text.len() {
606 let s = text.slice(self.last, text.len());
607 self.last = text.len();
612 let matched = text.slice(self.last, s);
620 /// Yields at most `N` substrings delimited by a regular expression match.
622 /// The last substring will be whatever remains after splitting.
624 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
625 /// of the string being split.
626 pub struct RegexSplitsN<'r, 't> {
627 splits: RegexSplits<'r, 't>,
632 impl<'r, 't> Iterator<&'t str> for RegexSplitsN<'r, 't> {
633 fn next(&mut self) -> Option<&'t str> {
634 let text = self.splits.finder.search;
635 if self.cur >= self.limit {
639 if self.cur >= self.limit {
640 Some(text.slice(self.splits.last, text.len()))
648 /// Captures represents a group of captured strings for a single match.
650 /// The 0th capture always corresponds to the entire match. Each subsequent
651 /// index corresponds to the next capture group in the regex.
652 /// If a capture group is named, then the matched string is *also* available
653 /// via the `name` method. (Note that the 0th capture is always unnamed and so
654 /// must be accessed with the `at` method.)
656 /// Positions returned from a capture group are always byte indices.
658 /// `'t` is the lifetime of the matched text.
659 pub struct Captures<'t> {
662 named: Option<HashMap<String, uint>>,
665 impl<'t> Captures<'t> {
666 #[allow(experimental)]
667 fn new(re: &Regex, search: &'t str, locs: CaptureLocs)
668 -> Option<Captures<'t>> {
669 if !has_match(&locs) {
674 if re.names_len() == 0 {
677 let mut named = HashMap::new();
678 for (i, name) in re.names_iter().enumerate() {
682 named.insert(name, i);
695 /// Returns the start and end positions of the Nth capture group.
696 /// Returns `None` if `i` is not a valid capture group or if the capture
697 /// group did not match anything.
698 /// The positions returned are *always* byte indices with respect to the
699 /// original string matched.
700 pub fn pos(&self, i: uint) -> Option<(uint, uint)> {
701 let (s, e) = (i * 2, i * 2 + 1);
702 if e >= self.locs.len() || self.locs.get(s).is_none() {
703 // VM guarantees that each pair of locations are both Some or None.
706 Some((self.locs.get(s).unwrap(), self.locs.get(e).unwrap()))
709 /// Returns the matched string for the capture group `i`.
710 /// If `i` isn't a valid capture group or didn't match anything, then the
711 /// empty string is returned.
712 pub fn at(&self, i: uint) -> &'t str {
716 self.text.slice(s, e)
721 /// Returns the matched string for the capture group named `name`.
722 /// If `name` isn't a valid capture group or didn't match anything, then
723 /// the empty string is returned.
724 pub fn name(&self, name: &str) -> &'t str {
728 match h.find_equiv(&name) {
730 Some(i) => self.at(*i),
736 /// Creates an iterator of all the capture groups in order of appearance
737 /// in the regular expression.
738 pub fn iter(&'t self) -> SubCaptures<'t> {
739 SubCaptures { idx: 0, caps: self, }
742 /// Creates an iterator of all the capture group positions in order of
743 /// appearance in the regular expression. Positions are byte indices
744 /// in terms of the original string matched.
745 pub fn iter_pos(&'t self) -> SubCapturesPos<'t> {
746 SubCapturesPos { idx: 0, caps: self, }
749 /// Expands all instances of `$name` in `text` to the corresponding capture
752 /// `name` may be an integer corresponding to the index of the
753 /// capture group (counted by order of opening parenthesis where `0` is the
754 /// entire match) or it can be a name (consisting of letters, digits or
755 /// underscores) corresponding to a named capture group.
757 /// If `name` isn't a valid capture group (whether the name doesn't exist or
758 /// isn't a valid index), then it is replaced with the empty string.
760 /// To write a literal `$` use `$$`.
761 pub fn expand(&self, text: &str) -> String {
762 // How evil can you get?
763 // FIXME: Don't use regexes for this. It's completely unnecessary.
764 let re = Regex::new(r"(^|[^$]|\b)\$(\w+)").unwrap();
765 let text = re.replace_all(text, |refs: &Captures| -> String {
766 let (pre, name) = (refs.at(1), refs.at(2));
768 match from_str::<uint>(name.as_slice()) {
769 None => self.name(name).to_string(),
770 Some(i) => self.at(i).to_string(),
773 let re = Regex::new(r"\$\$").unwrap();
774 re.replace_all(text.as_slice(), NoExpand("$"))
778 impl<'t> Container for Captures<'t> {
779 /// Returns the number of captured groups.
781 fn len(&self) -> uint {
786 /// An iterator over capture groups for a particular match of a regular
789 /// `'t` is the lifetime of the matched text.
790 pub struct SubCaptures<'t> {
792 caps: &'t Captures<'t>,
795 impl<'t> Iterator<&'t str> for SubCaptures<'t> {
796 fn next(&mut self) -> Option<&'t str> {
797 if self.idx < self.caps.len() {
799 Some(self.caps.at(self.idx - 1))
806 /// An iterator over capture group positions for a particular match of a
807 /// regular expression.
809 /// Positions are byte indices in terms of the original string matched.
811 /// `'t` is the lifetime of the matched text.
812 pub struct SubCapturesPos<'t> {
814 caps: &'t Captures<'t>,
817 impl<'t> Iterator<Option<(uint, uint)>> for SubCapturesPos<'t> {
818 fn next(&mut self) -> Option<Option<(uint, uint)>> {
819 if self.idx < self.caps.len() {
821 Some(self.caps.pos(self.idx - 1))
828 /// An iterator that yields all non-overlapping capture groups matching a
829 /// particular regular expression.
831 /// The iterator stops when no more matches can be found.
833 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
834 /// of the matched string.
835 pub struct FindCaptures<'r, 't> {
838 last_match: Option<uint>,
842 impl<'r, 't> Iterator<Captures<'t>> for FindCaptures<'r, 't> {
843 fn next(&mut self) -> Option<Captures<'t>> {
844 if self.last_end > self.search.len() {
848 let caps = exec_slice(self.re, Submatches, self.search,
849 self.last_end, self.search.len());
851 if !has_match(&caps) {
854 (caps.get(0).unwrap(), caps.get(1).unwrap())
857 // Don't accept empty matches immediately following a match.
858 // i.e., no infinite loops please.
859 if e == s && Some(self.last_end) == self.last_match {
864 self.last_match = Some(self.last_end);
865 Captures::new(self.re, self.search, caps)
869 /// An iterator over all non-overlapping matches for a particular string.
871 /// The iterator yields a tuple of integers corresponding to the start and end
872 /// of the match. The indices are byte offsets. The iterator stops when no more
873 /// matches can be found.
875 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
876 /// of the matched string.
877 pub struct FindMatches<'r, 't> {
880 last_match: Option<uint>,
884 impl<'r, 't> Iterator<(uint, uint)> for FindMatches<'r, 't> {
885 fn next(&mut self) -> Option<(uint, uint)> {
886 if self.last_end > self.search.len() {
890 let caps = exec_slice(self.re, Location, self.search,
891 self.last_end, self.search.len());
893 if !has_match(&caps) {
896 (caps.get(0).unwrap(), caps.get(1).unwrap())
899 // Don't accept empty matches immediately following a match.
900 // i.e., no infinite loops please.
901 if e == s && Some(self.last_end) == self.last_match {
906 self.last_match = Some(self.last_end);
911 fn exec(re: &Regex, which: MatchKind, input: &str) -> CaptureLocs {
912 exec_slice(re, which, input, 0, input.len())
915 fn exec_slice(re: &Regex, which: MatchKind,
916 input: &str, s: uint, e: uint) -> CaptureLocs {
918 Dynamic(Dynamic { ref prog, .. }) => vm::run(which, prog, input, s, e),
919 Native(Native { prog, .. }) => prog(which, input, s, e),
924 fn has_match(caps: &CaptureLocs) -> bool {
925 caps.len() >= 2 && caps.get(0).is_some() && caps.get(1).is_some()