]> git.lizzy.rs Git - rust.git/blob - src/libregex/re.rs
core: rename strbuf::StrBuf to string::String
[rust.git] / src / libregex / re.rs
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.
4 //
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.
10
11 use collections::HashMap;
12 use std::fmt;
13 use std::from_str::from_str;
14 use std::str::{MaybeOwned, Owned, Slice};
15
16 use compile::Program;
17 use parse;
18 use vm;
19 use vm::{CaptureLocs, MatchKind, Exists, Location, Submatches};
20
21 /// Escapes all regular expression meta characters in `text` so that it may be
22 /// safely used in a regular expression as a literal string.
23 pub fn quote(text: &str) -> String {
24     let mut quoted = String::with_capacity(text.len());
25     for c in text.chars() {
26         if parse::is_punct(c) {
27             quoted.push_char('\\')
28         }
29         quoted.push_char(c);
30     }
31     quoted
32 }
33
34 /// Tests if the given regular expression matches somewhere in the text given.
35 ///
36 /// If there was a problem compiling the regular expression, an error is
37 /// returned.
38 ///
39 /// To find submatches, split or replace text, you'll need to compile an
40 /// expression first.
41 ///
42 /// Note that you should prefer the `regex!` macro when possible. For example,
43 /// `regex!("...").is_match("...")`.
44 pub fn is_match(regex: &str, text: &str) -> Result<bool, parse::Error> {
45     Regex::new(regex).map(|r| r.is_match(text))
46 }
47
48 /// Regex is a compiled regular expression, represented as either a sequence
49 /// of bytecode instructions (dynamic) or as a specialized Rust function
50 /// (native). It can be used to search, split
51 /// or replace text. All searching is done with an implicit `.*?` at the
52 /// beginning and end of an expression. To force an expression to match the
53 /// whole string (or a prefix or a suffix), you must use an anchor like `^` or
54 /// `$` (or `\A` and `\z`).
55 ///
56 /// While this crate will handle Unicode strings (whether in the regular
57 /// expression or in the search text), all positions returned are **byte
58 /// indices**. Every byte index is guaranteed to be at a UTF8 codepoint
59 /// boundary.
60 ///
61 /// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a
62 /// compiled regular expression and text to search, respectively.
63 ///
64 /// The only methods that allocate new strings are the string replacement
65 /// methods. All other methods (searching and splitting) return borrowed
66 /// pointers into the string given.
67 ///
68 /// # Examples
69 ///
70 /// Find the location of a US phone number:
71 ///
72 /// ```rust
73 /// # use regex::Regex;
74 /// let re = match Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}") {
75 ///     Ok(re) => re,
76 ///     Err(err) => fail!("{}", err),
77 /// };
78 /// assert_eq!(re.find("phone: 111-222-3333"), Some((7, 19)));
79 /// ```
80 ///
81 /// You can also use the `regex!` macro to compile a regular expression when
82 /// you compile your program:
83 ///
84 /// ```rust
85 /// #![feature(phase)]
86 /// extern crate regex;
87 /// #[phase(syntax)] extern crate regex_macros;
88 ///
89 /// fn main() {
90 ///     let re = regex!(r"\d+");
91 ///     assert_eq!(re.find("123 abc"), Some((0, 3)));
92 /// }
93 /// ```
94 ///
95 /// Given an incorrect regular expression, `regex!` will cause the Rust
96 /// compiler to produce a compile time error.
97 /// Note that `regex!` will compile the expression to native Rust code, which
98 /// makes it much faster when searching text.
99 /// More details about the `regex!` macro can be found in the `regex` crate
100 /// documentation.
101 #[deriving(Clone)]
102 #[allow(visible_private_types)]
103 pub struct Regex {
104     /// The representation of `Regex` is exported to support the `regex!`
105     /// syntax extension. Do not rely on it.
106     ///
107     /// See the comments for the `program` module in `lib.rs` for a more
108     /// detailed explanation for what `regex!` requires.
109     #[doc(hidden)]
110     pub original: String,
111     #[doc(hidden)]
112     pub names: Vec<Option<String>>,
113     #[doc(hidden)]
114     pub p: MaybeNative,
115 }
116
117 impl fmt::Show for Regex {
118     /// Shows the original regular expression.
119     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120         write!(f, "{}", self.original)
121     }
122 }
123
124 pub enum MaybeNative {
125     Dynamic(Program),
126     Native(fn(MatchKind, &str, uint, uint) -> Vec<Option<uint>>),
127 }
128
129 impl Clone for MaybeNative {
130     fn clone(&self) -> MaybeNative {
131         match *self {
132             Dynamic(ref p) => Dynamic(p.clone()),
133             Native(fp) => Native(fp),
134         }
135     }
136 }
137
138 impl Regex {
139     /// Compiles a dynamic regular expression. Once compiled, it can be
140     /// used repeatedly to search, split or replace text in a string.
141     ///
142     /// When possible, you should prefer the `regex!` macro since it is
143     /// safer and always faster.
144     ///
145     /// If an invalid expression is given, then an error is returned.
146     pub fn new(re: &str) -> Result<Regex, parse::Error> {
147         let ast = try!(parse::parse(re));
148         let (prog, names) = Program::new(ast);
149         Ok(Regex {
150             original: re.to_strbuf(),
151             names: names, p: Dynamic(prog),
152         })
153     }
154
155     /// Returns true if and only if the regex matches the string given.
156     ///
157     /// # Example
158     ///
159     /// Test if some text contains at least one word with exactly 13
160     /// characters:
161     ///
162     /// ```rust
163     /// # #![feature(phase)]
164     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
165     /// # fn main() {
166     /// let text = "I categorically deny having triskaidekaphobia.";
167     /// let matched = regex!(r"\b\w{13}\b").is_match(text);
168     /// assert!(matched);
169     /// # }
170     /// ```
171     pub fn is_match(&self, text: &str) -> bool {
172         has_match(&exec(self, Exists, text))
173     }
174
175     /// Returns the start and end byte range of the leftmost-first match in
176     /// `text`. If no match exists, then `None` is returned.
177     ///
178     /// Note that this should only be used if you want to discover the position
179     /// of the match. Testing the existence of a match is faster if you use
180     /// `is_match`.
181     ///
182     /// # Example
183     ///
184     /// Find the start and end location of every word with exactly 13
185     /// characters:
186     ///
187     /// ```rust
188     /// # #![feature(phase)]
189     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
190     /// # fn main() {
191     /// let text = "I categorically deny having triskaidekaphobia.";
192     /// let pos = regex!(r"\b\w{13}\b").find(text);
193     /// assert_eq!(pos, Some((2, 15)));
194     /// # }
195     /// ```
196     pub fn find(&self, text: &str) -> Option<(uint, uint)> {
197         let caps = exec(self, Location, text);
198         if has_match(&caps) {
199             Some((caps.get(0).unwrap(), caps.get(1).unwrap()))
200         } else {
201             None
202         }
203     }
204
205     /// Returns an iterator for each successive non-overlapping match in
206     /// `text`, returning the start and end byte indices with respect to
207     /// `text`.
208     ///
209     /// # Example
210     ///
211     /// Find the start and end location of the first word with exactly 13
212     /// characters:
213     ///
214     /// ```rust
215     /// # #![feature(phase)]
216     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
217     /// # fn main() {
218     /// let text = "Retroactively relinquishing remunerations is reprehensible.";
219     /// for pos in regex!(r"\b\w{13}\b").find_iter(text) {
220     ///     println!("{}", pos);
221     /// }
222     /// // Output:
223     /// // (0, 13)
224     /// // (14, 27)
225     /// // (28, 41)
226     /// // (45, 58)
227     /// # }
228     /// ```
229     pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindMatches<'r, 't> {
230         FindMatches {
231             re: self,
232             search: text,
233             last_end: 0,
234             last_match: None,
235         }
236     }
237
238     /// Returns the capture groups corresponding to the leftmost-first
239     /// match in `text`. Capture group `0` always corresponds to the entire
240     /// match. If no match is found, then `None` is returned.
241     ///
242     /// You should only use `captures` if you need access to submatches.
243     /// Otherwise, `find` is faster for discovering the location of the overall
244     /// match.
245     ///
246     /// # Examples
247     ///
248     /// Say you have some text with movie names and their release years,
249     /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text
250     /// looking like that, while also extracting the movie name and its release
251     /// year separately.
252     ///
253     /// ```rust
254     /// # #![feature(phase)]
255     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
256     /// # fn main() {
257     /// let re = regex!(r"'([^']+)'\s+\((\d{4})\)");
258     /// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
259     /// let caps = re.captures(text).unwrap();
260     /// assert_eq!(caps.at(1), "Citizen Kane");
261     /// assert_eq!(caps.at(2), "1941");
262     /// assert_eq!(caps.at(0), "'Citizen Kane' (1941)");
263     /// # }
264     /// ```
265     ///
266     /// Note that the full match is at capture group `0`. Each subsequent
267     /// capture group is indexed by the order of its opening `(`.
268     ///
269     /// We can make this example a bit clearer by using *named* capture groups:
270     ///
271     /// ```rust
272     /// # #![feature(phase)]
273     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
274     /// # fn main() {
275     /// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)");
276     /// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
277     /// let caps = re.captures(text).unwrap();
278     /// assert_eq!(caps.name("title"), "Citizen Kane");
279     /// assert_eq!(caps.name("year"), "1941");
280     /// assert_eq!(caps.at(0), "'Citizen Kane' (1941)");
281     /// # }
282     /// ```
283     ///
284     /// Here we name the capture groups, which we can access with the `name`
285     /// method. Note that the named capture groups are still accessible with
286     /// `at`.
287     ///
288     /// The `0`th capture group is always unnamed, so it must always be
289     /// accessed with `at(0)`.
290     pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> {
291         let caps = exec(self, Submatches, text);
292         Captures::new(self, text, caps)
293     }
294
295     /// Returns an iterator over all the non-overlapping capture groups matched
296     /// in `text`. This is operationally the same as `find_iter` (except it
297     /// yields information about submatches).
298     ///
299     /// # Example
300     ///
301     /// We can use this to find all movie titles and their release years in
302     /// some text, where the movie is formatted like "'Title' (xxxx)":
303     ///
304     /// ```rust
305     /// # #![feature(phase)]
306     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
307     /// # fn main() {
308     /// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)");
309     /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931).";
310     /// for caps in re.captures_iter(text) {
311     ///     println!("Movie: {}, Released: {}", caps.name("title"), caps.name("year"));
312     /// }
313     /// // Output:
314     /// // Movie: Citizen Kane, Released: 1941
315     /// // Movie: The Wizard of Oz, Released: 1939
316     /// // Movie: M, Released: 1931
317     /// # }
318     /// ```
319     pub fn captures_iter<'r, 't>(&'r self, text: &'t str)
320                                 -> FindCaptures<'r, 't> {
321         FindCaptures {
322             re: self,
323             search: text,
324             last_match: None,
325             last_end: 0,
326         }
327     }
328
329     /// Returns an iterator of substrings of `text` delimited by a match
330     /// of the regular expression.
331     /// Namely, each element of the iterator corresponds to text that *isn't*
332     /// matched by the regular expression.
333     ///
334     /// This method will *not* copy the text given.
335     ///
336     /// # Example
337     ///
338     /// To split a string delimited by arbitrary amounts of spaces or tabs:
339     ///
340     /// ```rust
341     /// # #![feature(phase)]
342     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
343     /// # fn main() {
344     /// let re = regex!(r"[ \t]+");
345     /// let fields: Vec<&str> = re.split("a b \t  c\td    e").collect();
346     /// assert_eq!(fields, vec!("a", "b", "c", "d", "e"));
347     /// # }
348     /// ```
349     pub fn split<'r, 't>(&'r self, text: &'t str) -> RegexSplits<'r, 't> {
350         RegexSplits {
351             finder: self.find_iter(text),
352             last: 0,
353         }
354     }
355
356     /// Returns an iterator of at most `limit` substrings of `text` delimited
357     /// by a match of the regular expression. (A `limit` of `0` will return no
358     /// substrings.)
359     /// Namely, each element of the iterator corresponds to text that *isn't*
360     /// matched by the regular expression.
361     /// The remainder of the string that is not split will be the last element
362     /// in the iterator.
363     ///
364     /// This method will *not* copy the text given.
365     ///
366     /// # Example
367     ///
368     /// Get the first two words in some text:
369     ///
370     /// ```rust
371     /// # #![feature(phase)]
372     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
373     /// # fn main() {
374     /// let re = regex!(r"\W+");
375     /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect();
376     /// assert_eq!(fields, vec!("Hey", "How", "are you?"));
377     /// # }
378     /// ```
379     pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: uint)
380                          -> RegexSplitsN<'r, 't> {
381         RegexSplitsN {
382             splits: self.split(text),
383             cur: 0,
384             limit: limit,
385         }
386     }
387
388     /// Replaces the leftmost-first match with the replacement provided.
389     /// The replacement can be a regular string (where `$N` and `$name` are
390     /// expanded to match capture groups) or a function that takes the matches'
391     /// `Captures` and returns the replaced string.
392     ///
393     /// If no match is found, then a copy of the string is returned unchanged.
394     ///
395     /// # Examples
396     ///
397     /// Note that this function is polymorphic with respect to the replacement.
398     /// In typical usage, this can just be a normal string:
399     ///
400     /// ```rust
401     /// # #![feature(phase)]
402     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
403     /// # fn main() {
404     /// let re = regex!("[^01]+");
405     /// assert_eq!(re.replace("1078910", "").as_slice(), "1010");
406     /// # }
407     /// ```
408     ///
409     /// But anything satisfying the `Replacer` trait will work. For example,
410     /// a closure of type `|&Captures| -> String` provides direct access to the
411     /// captures corresponding to a match. This allows one to access
412     /// submatches easily:
413     ///
414     /// ```rust
415     /// # #![feature(phase)]
416     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
417     /// # use regex::Captures; fn main() {
418     /// let re = regex!(r"([^,\s]+),\s+(\S+)");
419     /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| {
420     ///     format_strbuf!("{} {}", caps.at(2), caps.at(1))
421     /// });
422     /// assert_eq!(result.as_slice(), "Bruce Springsteen");
423     /// # }
424     /// ```
425     ///
426     /// But this is a bit cumbersome to use all the time. Instead, a simple
427     /// syntax is supported that expands `$name` into the corresponding capture
428     /// group. Here's the last example, but using this expansion technique
429     /// with named capture groups:
430     ///
431     /// ```rust
432     /// # #![feature(phase)]
433     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
434     /// # fn main() {
435     /// let re = regex!(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)");
436     /// let result = re.replace("Springsteen, Bruce", "$first $last");
437     /// assert_eq!(result.as_slice(), "Bruce Springsteen");
438     /// # }
439     /// ```
440     ///
441     /// Note that using `$2` instead of `$first` or `$1` instead of `$last`
442     /// would produce the same result. To write a literal `$` use `$$`.
443     ///
444     /// Finally, sometimes you just want to replace a literal string with no
445     /// submatch expansion. This can be done by wrapping a string with
446     /// `NoExpand`:
447     ///
448     /// ```rust
449     /// # #![feature(phase)]
450     /// # extern crate regex; #[phase(syntax)] extern crate regex_macros;
451     /// # fn main() {
452     /// use regex::NoExpand;
453     ///
454     /// let re = regex!(r"(?P<last>[^,\s]+),\s+(\S+)");
455     /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last"));
456     /// assert_eq!(result.as_slice(), "$2 $last");
457     /// # }
458     /// ```
459     pub fn replace<R: Replacer>(&self, text: &str, rep: R) -> String {
460         self.replacen(text, 1, rep)
461     }
462
463     /// Replaces all non-overlapping matches in `text` with the
464     /// replacement provided. This is the same as calling `replacen` with
465     /// `limit` set to `0`.
466     ///
467     /// See the documentation for `replace` for details on how to access
468     /// submatches in the replacement string.
469     pub fn replace_all<R: Replacer>(&self, text: &str, rep: R) -> String {
470         self.replacen(text, 0, rep)
471     }
472
473     /// Replaces at most `limit` non-overlapping matches in `text` with the
474     /// replacement provided. If `limit` is 0, then all non-overlapping matches
475     /// are replaced.
476     ///
477     /// See the documentation for `replace` for details on how to access
478     /// submatches in the replacement string.
479     pub fn replacen<R: Replacer>
480                    (&self, text: &str, limit: uint, mut rep: R) -> String {
481         let mut new = String::with_capacity(text.len());
482         let mut last_match = 0u;
483
484         for (i, cap) in self.captures_iter(text).enumerate() {
485             // It'd be nicer to use the 'take' iterator instead, but it seemed
486             // awkward given that '0' => no limit.
487             if limit > 0 && i >= limit {
488                 break
489             }
490
491             let (s, e) = cap.pos(0).unwrap(); // captures only reports matches
492             new.push_str(text.slice(last_match, s));
493             new.push_str(rep.reg_replace(&cap).as_slice());
494             last_match = e;
495         }
496         new.append(text.slice(last_match, text.len()))
497     }
498 }
499
500 /// NoExpand indicates literal string replacement.
501 ///
502 /// It can be used with `replace` and `replace_all` to do a literal
503 /// string replacement without expanding `$name` to their corresponding
504 /// capture groups.
505 ///
506 /// `'r` is the lifetime of the literal text.
507 pub struct NoExpand<'t>(pub &'t str);
508
509 /// Replacer describes types that can be used to replace matches in a string.
510 pub trait Replacer {
511     /// Returns a possibly owned string that is used to replace the match
512     /// corresponding the the `caps` capture group.
513     ///
514     /// The `'a` lifetime refers to the lifetime of a borrowed string when
515     /// a new owned string isn't needed (e.g., for `NoExpand`).
516     fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a>;
517 }
518
519 impl<'t> Replacer for NoExpand<'t> {
520     fn reg_replace<'a>(&'a mut self, _: &Captures) -> MaybeOwned<'a> {
521         let NoExpand(s) = *self;
522         Slice(s)
523     }
524 }
525
526 impl<'t> Replacer for &'t str {
527     fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a> {
528         Owned(caps.expand(*self).into_owned())
529     }
530 }
531
532 impl<'a> Replacer for |&Captures|: 'a -> String {
533     fn reg_replace<'r>(&'r mut self, caps: &Captures) -> MaybeOwned<'r> {
534         Owned((*self)(caps).into_owned())
535     }
536 }
537
538 /// Yields all substrings delimited by a regular expression match.
539 ///
540 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
541 /// of the string being split.
542 pub struct RegexSplits<'r, 't> {
543     finder: FindMatches<'r, 't>,
544     last: uint,
545 }
546
547 impl<'r, 't> Iterator<&'t str> for RegexSplits<'r, 't> {
548     fn next(&mut self) -> Option<&'t str> {
549         let text = self.finder.search;
550         match self.finder.next() {
551             None => {
552                 if self.last >= text.len() {
553                     None
554                 } else {
555                     let s = text.slice(self.last, text.len());
556                     self.last = text.len();
557                     Some(s)
558                 }
559             }
560             Some((s, e)) => {
561                 let matched = text.slice(self.last, s);
562                 self.last = e;
563                 Some(matched)
564             }
565         }
566     }
567 }
568
569 /// Yields at most `N` substrings delimited by a regular expression match.
570 ///
571 /// The last substring will be whatever remains after splitting.
572 ///
573 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
574 /// of the string being split.
575 pub struct RegexSplitsN<'r, 't> {
576     splits: RegexSplits<'r, 't>,
577     cur: uint,
578     limit: uint,
579 }
580
581 impl<'r, 't> Iterator<&'t str> for RegexSplitsN<'r, 't> {
582     fn next(&mut self) -> Option<&'t str> {
583         let text = self.splits.finder.search;
584         if self.cur >= self.limit {
585             None
586         } else {
587             self.cur += 1;
588             if self.cur >= self.limit {
589                 Some(text.slice(self.splits.last, text.len()))
590             } else {
591                 self.splits.next()
592             }
593         }
594     }
595 }
596
597 /// Captures represents a group of captured strings for a single match.
598 ///
599 /// The 0th capture always corresponds to the entire match. Each subsequent
600 /// index corresponds to the next capture group in the regex.
601 /// If a capture group is named, then the matched string is *also* available
602 /// via the `name` method. (Note that the 0th capture is always unnamed and so
603 /// must be accessed with the `at` method.)
604 ///
605 /// Positions returned from a capture group are always byte indices.
606 ///
607 /// `'t` is the lifetime of the matched text.
608 pub struct Captures<'t> {
609     text: &'t str,
610     locs: CaptureLocs,
611     named: Option<HashMap<String, uint>>,
612 }
613
614 impl<'t> Captures<'t> {
615     fn new(re: &Regex, search: &'t str, locs: CaptureLocs)
616           -> Option<Captures<'t>> {
617         if !has_match(&locs) {
618             return None
619         }
620
621         let named =
622             if re.names.len() == 0 {
623                 None
624             } else {
625                 let mut named = HashMap::new();
626                 for (i, name) in re.names.iter().enumerate() {
627                     match name {
628                         &None => {},
629                         &Some(ref name) => {
630                             named.insert(name.to_strbuf(), i);
631                         }
632                     }
633                 }
634                 Some(named)
635             };
636         Some(Captures {
637             text: search,
638             locs: locs,
639             named: named,
640         })
641     }
642
643     /// Returns the start and end positions of the Nth capture group.
644     /// Returns `None` if `i` is not a valid capture group or if the capture
645     /// group did not match anything.
646     /// The positions returned are *always* byte indices with respect to the
647     /// original string matched.
648     pub fn pos(&self, i: uint) -> Option<(uint, uint)> {
649         let (s, e) = (i * 2, i * 2 + 1);
650         if e >= self.locs.len() || self.locs.get(s).is_none() {
651             // VM guarantees that each pair of locations are both Some or None.
652             return None
653         }
654         Some((self.locs.get(s).unwrap(), self.locs.get(e).unwrap()))
655     }
656
657     /// Returns the matched string for the capture group `i`.
658     /// If `i` isn't a valid capture group or didn't match anything, then the
659     /// empty string is returned.
660     pub fn at(&self, i: uint) -> &'t str {
661         match self.pos(i) {
662             None => "",
663             Some((s, e)) => {
664                 self.text.slice(s, e)
665             }
666         }
667     }
668
669     /// Returns the matched string for the capture group named `name`.
670     /// If `name` isn't a valid capture group or didn't match anything, then
671     /// the empty string is returned.
672     pub fn name(&self, name: &str) -> &'t str {
673         match self.named {
674             None => "",
675             Some(ref h) => {
676                 match h.find_equiv(&name) {
677                     None => "",
678                     Some(i) => self.at(*i),
679                 }
680             }
681         }
682     }
683
684     /// Creates an iterator of all the capture groups in order of appearance
685     /// in the regular expression.
686     pub fn iter(&'t self) -> SubCaptures<'t> {
687         SubCaptures { idx: 0, caps: self, }
688     }
689
690     /// Creates an iterator of all the capture group positions in order of
691     /// appearance in the regular expression. Positions are byte indices
692     /// in terms of the original string matched.
693     pub fn iter_pos(&'t self) -> SubCapturesPos<'t> {
694         SubCapturesPos { idx: 0, caps: self, }
695     }
696
697     /// Expands all instances of `$name` in `text` to the corresponding capture
698     /// group `name`.
699     ///
700     /// `name` may be an integer corresponding to the index of the
701     /// capture group (counted by order of opening parenthesis where `0` is the
702     /// entire match) or it can be a name (consisting of letters, digits or
703     /// underscores) corresponding to a named capture group.
704     ///
705     /// If `name` isn't a valid capture group (whether the name doesn't exist or
706     /// isn't a valid index), then it is replaced with the empty string.
707     ///
708     /// To write a literal `$` use `$$`.
709     pub fn expand(&self, text: &str) -> String {
710         // How evil can you get?
711         // FIXME: Don't use regexes for this. It's completely unnecessary.
712         let re = Regex::new(r"(^|[^$]|\b)\$(\w+)").unwrap();
713         let text = re.replace_all(text, |refs: &Captures| -> String {
714             let (pre, name) = (refs.at(1), refs.at(2));
715             format_strbuf!("{}{}",
716                            pre,
717                            match from_str::<uint>(name.as_slice()) {
718                 None => self.name(name).to_strbuf(),
719                 Some(i) => self.at(i).to_strbuf(),
720             })
721         });
722         let re = Regex::new(r"\$\$").unwrap();
723         re.replace_all(text.as_slice(), NoExpand("$"))
724     }
725 }
726
727 impl<'t> Container for Captures<'t> {
728     /// Returns the number of captured groups.
729     #[inline]
730     fn len(&self) -> uint {
731         self.locs.len() / 2
732     }
733 }
734
735 /// An iterator over capture groups for a particular match of a regular
736 /// expression.
737 ///
738 /// `'t` is the lifetime of the matched text.
739 pub struct SubCaptures<'t> {
740     idx: uint,
741     caps: &'t Captures<'t>,
742 }
743
744 impl<'t> Iterator<&'t str> for SubCaptures<'t> {
745     fn next(&mut self) -> Option<&'t str> {
746         if self.idx < self.caps.len() {
747             self.idx += 1;
748             Some(self.caps.at(self.idx - 1))
749         } else {
750             None
751         }
752     }
753 }
754
755 /// An iterator over capture group positions for a particular match of a
756 /// regular expression.
757 ///
758 /// Positions are byte indices in terms of the original string matched.
759 ///
760 /// `'t` is the lifetime of the matched text.
761 pub struct SubCapturesPos<'t> {
762     idx: uint,
763     caps: &'t Captures<'t>,
764 }
765
766 impl<'t> Iterator<Option<(uint, uint)>> for SubCapturesPos<'t> {
767     fn next(&mut self) -> Option<Option<(uint, uint)>> {
768         if self.idx < self.caps.len() {
769             self.idx += 1;
770             Some(self.caps.pos(self.idx - 1))
771         } else {
772             None
773         }
774     }
775 }
776
777 /// An iterator that yields all non-overlapping capture groups matching a
778 /// particular regular expression. The iterator stops when no more matches can
779 /// be found.
780 ///
781 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
782 /// of the matched string.
783 pub struct FindCaptures<'r, 't> {
784     re: &'r Regex,
785     search: &'t str,
786     last_match: Option<uint>,
787     last_end: uint,
788 }
789
790 impl<'r, 't> Iterator<Captures<'t>> for FindCaptures<'r, 't> {
791     fn next(&mut self) -> Option<Captures<'t>> {
792         if self.last_end > self.search.len() {
793             return None
794         }
795
796         let caps = exec_slice(self.re, Submatches, self.search,
797                               self.last_end, self.search.len());
798         let (s, e) =
799             if !has_match(&caps) {
800                 return None
801             } else {
802                 (caps.get(0).unwrap(), caps.get(1).unwrap())
803             };
804
805         // Don't accept empty matches immediately following a match.
806         // i.e., no infinite loops please.
807         if e == s && Some(self.last_end) == self.last_match {
808             self.last_end += 1;
809             return self.next()
810         }
811         self.last_end = e;
812         self.last_match = Some(self.last_end);
813         Captures::new(self.re, self.search, caps)
814     }
815 }
816
817 /// An iterator over all non-overlapping matches for a particular string.
818 ///
819 /// The iterator yields a tuple of integers corresponding to the start and end
820 /// of the match. The indices are byte offsets. The iterator stops when no more
821 /// matches can be found.
822 ///
823 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
824 /// of the matched string.
825 pub struct FindMatches<'r, 't> {
826     re: &'r Regex,
827     search: &'t str,
828     last_match: Option<uint>,
829     last_end: uint,
830 }
831
832 impl<'r, 't> Iterator<(uint, uint)> for FindMatches<'r, 't> {
833     fn next(&mut self) -> Option<(uint, uint)> {
834         if self.last_end > self.search.len() {
835             return None
836         }
837
838         let caps = exec_slice(self.re, Location, self.search,
839                               self.last_end, self.search.len());
840         let (s, e) =
841             if !has_match(&caps) {
842                 return None
843             } else {
844                 (caps.get(0).unwrap(), caps.get(1).unwrap())
845             };
846
847         // Don't accept empty matches immediately following a match.
848         // i.e., no infinite loops please.
849         if e == s && Some(self.last_end) == self.last_match {
850             self.last_end += 1;
851             return self.next()
852         }
853         self.last_end = e;
854         self.last_match = Some(self.last_end);
855         Some((s, e))
856     }
857 }
858
859 fn exec(re: &Regex, which: MatchKind, input: &str) -> CaptureLocs {
860     exec_slice(re, which, input, 0, input.len())
861 }
862
863 fn exec_slice(re: &Regex, which: MatchKind,
864               input: &str, s: uint, e: uint) -> CaptureLocs {
865     match re.p {
866         Dynamic(ref prog) => vm::run(which, prog, input, s, e),
867         Native(exec) => exec(which, input, s, e),
868     }
869 }
870
871 #[inline]
872 fn has_match(caps: &CaptureLocs) -> bool {
873     caps.len() >= 2 && caps.get(0).is_some() && caps.get(1).is_some()
874 }