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