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