1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::NamesIter::*;
12 pub use self::Regex::*;
14 use std::borrow::IntoCow;
15 use std::collections::HashMap;
17 use std::string::CowString;
22 use vm::{CaptureLocs, MatchKind, Exists, Location, Submatches};
24 /// Escapes all regular expression meta characters in `text`.
26 /// The string returned may be safely used as a literal in a regular
28 pub fn quote(text: &str) -> String {
29 let mut quoted = String::with_capacity(text.len());
30 for c in text.chars() {
31 if parse::is_punct(c) {
39 /// Tests if the given regular expression matches somewhere in the text given.
41 /// If there was a problem compiling the regular expression, an error is
44 /// To find submatches, split or replace text, you'll need to compile an
47 /// Note that you should prefer the `regex!` macro when possible. For example,
48 /// `regex!("...").is_match("...")`.
49 pub fn is_match(regex: &str, text: &str) -> Result<bool, parse::Error> {
50 Regex::new(regex).map(|r| r.is_match(text))
53 /// A compiled regular expression
56 // The representation of `Regex` is exported to support the `regex!`
57 // syntax extension. Do not rely on it.
59 // See the comments for the `program` module in `lib.rs` for a more
60 // detailed explanation for what `regex!` requires.
69 pub struct ExDynamic {
71 names: Vec<Option<String>>,
80 pub original: &'static str,
82 pub names: &'static &'static [Option<&'static str>],
84 pub prog: fn(MatchKind, &str, uint, uint) -> Vec<Option<uint>>
87 impl Clone for ExNative {
88 fn clone(&self) -> ExNative {
93 impl fmt::Show for Regex {
94 /// Shows the original regular expression.
95 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 write!(f, "{}", self.as_str())
101 /// Compiles a dynamic regular expression. Once compiled, it can be
102 /// used repeatedly to search, split or replace text in a string.
104 /// When possible, you should prefer the `regex!` macro since it is
105 /// safer and always faster.
107 /// If an invalid expression is given, then an error is returned.
108 pub fn new(re: &str) -> Result<Regex, parse::Error> {
109 let ast = try!(parse::parse(re));
110 let (prog, names) = Program::new(ast);
111 Ok(Dynamic(ExDynamic {
112 original: re.to_string(),
118 /// Returns true if and only if the regex matches the string given.
119 pub fn is_match(&self, text: &str) -> bool {
120 has_match(&exec(self, Exists, text))
123 /// Returns the start and end byte range of the leftmost-first match in
124 /// `text`. If no match exists, then `None` is returned.
125 pub fn find(&self, text: &str) -> Option<(uint, uint)> {
126 let caps = exec(self, Location, text);
127 if has_match(&caps) {
128 Some((caps[0].unwrap(), caps[1].unwrap()))
134 /// Returns an iterator for each successive non-overlapping match in
135 /// `text`, returning the start and end byte indices with respect to
137 pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindMatches<'r, 't> {
146 /// Returns the capture groups corresponding to the leftmost-first
147 /// match in `text`. Capture group `0` always corresponds to the entire
148 /// match. If no match is found, then `None` is returned.
150 /// You should only use `captures` if you need access to submatches.
151 /// Otherwise, `find` is faster for discovering the location of the overall
153 pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> {
154 let caps = exec(self, Submatches, text);
155 Captures::new(self, text, caps)
158 /// Returns an iterator over all the non-overlapping capture groups matched
159 /// in `text`. This is operationally the same as `find_iter` (except it
160 /// yields information about submatches).
161 pub fn captures_iter<'r, 't>(&'r self, text: &'t str)
162 -> FindCaptures<'r, 't> {
171 /// Returns an iterator of substrings of `text` delimited by a match
172 /// of the regular expression.
173 /// Namely, each element of the iterator corresponds to text that *isn't*
174 /// matched by the regular expression.
176 /// This method will *not* copy the text given.
177 pub fn split<'r, 't>(&'r self, text: &'t str) -> RegexSplits<'r, 't> {
179 finder: self.find_iter(text),
184 /// Returns an iterator of at most `limit` substrings of `text` delimited
185 /// by a match of the regular expression. (A `limit` of `0` will return no
187 /// Namely, each element of the iterator corresponds to text that *isn't*
188 /// matched by the regular expression.
189 /// The remainder of the string that is not split will be the last element
192 /// This method will *not* copy the text given.
193 pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: uint)
194 -> RegexSplitsN<'r, 't> {
196 splits: self.split(text),
202 /// Replaces the leftmost-first match with the replacement provided.
203 /// The replacement can be a regular string (where `$N` and `$name` are
204 /// expanded to match capture groups) or a function that takes the matches'
205 /// `Captures` and returns the replaced string.
207 /// If no match is found, then a copy of the string is returned unchanged.
208 pub fn replace<R: Replacer>(&self, text: &str, rep: R) -> String {
209 self.replacen(text, 1, rep)
212 /// Replaces all non-overlapping matches in `text` with the
213 /// replacement provided. This is the same as calling `replacen` with
214 /// `limit` set to `0`.
216 /// See the documentation for `replace` for details on how to access
217 /// submatches in the replacement string.
218 pub fn replace_all<R: Replacer>(&self, text: &str, rep: R) -> String {
219 self.replacen(text, 0, rep)
222 /// Replaces at most `limit` non-overlapping matches in `text` with the
223 /// replacement provided. If `limit` is 0, then all non-overlapping matches
226 /// See the documentation for `replace` for details on how to access
227 /// submatches in the replacement string.
228 pub fn replacen<R: Replacer>
229 (&self, text: &str, limit: uint, mut rep: R) -> String {
230 let mut new = String::with_capacity(text.len());
231 let mut last_match = 0u;
233 for (i, cap) in self.captures_iter(text).enumerate() {
234 // It'd be nicer to use the 'take' iterator instead, but it seemed
235 // awkward given that '0' => no limit.
236 if limit > 0 && i >= limit {
240 let (s, e) = cap.pos(0).unwrap(); // captures only reports matches
241 new.push_str(text[last_match..s]);
242 new.push_str(rep.reg_replace(&cap)[]);
245 new.push_str(text[last_match..text.len()]);
249 /// Returns the original string of this regex.
250 pub fn as_str<'a>(&'a self) -> &'a str {
252 Dynamic(ExDynamic { ref original, .. }) => original[],
253 Native(ExNative { ref original, .. }) => original[],
259 pub fn names_iter<'a>(&'a self) -> NamesIter<'a> {
261 Native(ref n) => NamesIterNative(n.names.iter()),
262 Dynamic(ref d) => NamesIterDynamic(d.names.iter())
266 fn names_len(&self) -> uint {
268 Native(ref n) => n.names.len(),
269 Dynamic(ref d) => d.names.len()
276 pub enum NamesIter<'a> {
277 NamesIterNative(::std::slice::Iter<'a, Option<&'static str>>),
278 NamesIterDynamic(::std::slice::Iter<'a, Option<String>>)
281 impl<'a> Iterator for NamesIter<'a> {
282 type Item = Option<String>;
284 fn next(&mut self) -> Option<Option<String>> {
286 NamesIterNative(ref mut i) => i.next().map(|x| x.map(|s| s.to_string())),
287 NamesIterDynamic(ref mut i) => i.next().map(|x| x.as_ref().map(|s| s.to_string())),
292 /// NoExpand indicates literal string replacement.
294 /// It can be used with `replace` and `replace_all` to do a literal
295 /// string replacement without expanding `$name` to their corresponding
298 /// `'r` is the lifetime of the literal text.
299 pub struct NoExpand<'t>(pub &'t str);
301 /// Replacer describes types that can be used to replace matches in a string.
303 /// Returns a possibly owned string that is used to replace the match
304 /// corresponding to the `caps` capture group.
306 /// The `'a` lifetime refers to the lifetime of a borrowed string when
307 /// a new owned string isn't needed (e.g., for `NoExpand`).
308 fn reg_replace<'a>(&'a mut self, caps: &Captures) -> CowString<'a>;
311 impl<'t> Replacer for NoExpand<'t> {
312 fn reg_replace<'a>(&'a mut self, _: &Captures) -> CowString<'a> {
313 let NoExpand(s) = *self;
318 impl<'t> Replacer for &'t str {
319 fn reg_replace<'a>(&'a mut self, caps: &Captures) -> CowString<'a> {
320 caps.expand(*self).into_cow()
324 impl<F> Replacer for F where F: FnMut(&Captures) -> String {
325 fn reg_replace<'a>(&'a mut self, caps: &Captures) -> CowString<'a> {
326 (*self)(caps).into_cow()
330 /// Yields all substrings delimited by a regular expression match.
332 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
333 /// of the string being split.
335 pub struct RegexSplits<'r, 't> {
336 finder: FindMatches<'r, 't>,
340 impl<'r, 't> Iterator for RegexSplits<'r, 't> {
343 fn next(&mut self) -> Option<&'t str> {
344 let text = self.finder.search;
345 match self.finder.next() {
347 if self.last >= text.len() {
350 let s = text[self.last..text.len()];
351 self.last = text.len();
356 let matched = text[self.last..s];
364 /// Yields at most `N` substrings delimited by a regular expression match.
366 /// The last substring will be whatever remains after splitting.
368 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
369 /// of the string being split.
371 pub struct RegexSplitsN<'r, 't> {
372 splits: RegexSplits<'r, 't>,
377 impl<'r, 't> Iterator for RegexSplitsN<'r, 't> {
380 fn next(&mut self) -> Option<&'t str> {
381 let text = self.splits.finder.search;
382 if self.cur >= self.limit {
386 if self.cur >= self.limit {
387 Some(text[self.splits.last..text.len()])
395 /// Captures represents a group of captured strings for a single match.
397 /// The 0th capture always corresponds to the entire match. Each subsequent
398 /// index corresponds to the next capture group in the regex.
399 /// If a capture group is named, then the matched string is *also* available
400 /// via the `name` method. (Note that the 0th capture is always unnamed and so
401 /// must be accessed with the `at` method.)
403 /// Positions returned from a capture group are always byte indices.
405 /// `'t` is the lifetime of the matched text.
406 pub struct Captures<'t> {
409 named: Option<HashMap<String, uint>>,
412 impl<'t> Captures<'t> {
413 #[allow(experimental)]
414 fn new(re: &Regex, search: &'t str, locs: CaptureLocs)
415 -> Option<Captures<'t>> {
416 if !has_match(&locs) {
421 if re.names_len() == 0 {
424 let mut named = HashMap::new();
425 for (i, name) in re.names_iter().enumerate() {
429 named.insert(name, i);
442 /// Returns the start and end positions of the Nth capture group.
443 /// Returns `None` if `i` is not a valid capture group or if the capture
444 /// group did not match anything.
445 /// The positions returned are *always* byte indices with respect to the
446 /// original string matched.
447 pub fn pos(&self, i: uint) -> Option<(uint, uint)> {
448 let (s, e) = (i * 2, i * 2 + 1);
449 if e >= self.locs.len() || self.locs[s].is_none() {
450 // VM guarantees that each pair of locations are both Some or None.
453 Some((self.locs[s].unwrap(), self.locs[e].unwrap()))
456 /// Returns the matched string for the capture group `i`. If `i` isn't
457 /// a valid capture group or didn't match anything, then `None` is
459 pub fn at(&self, i: uint) -> Option<&'t str> {
462 Some((s, e)) => Some(self.text.slice(s, e))
466 /// Returns the matched string for the capture group named `name`. If
467 /// `name` isn't a valid capture group or didn't match anything, then
468 /// `None` is returned.
469 pub fn name(&self, name: &str) -> Option<&'t str> {
475 Some(i) => self.at(*i),
481 /// Creates an iterator of all the capture groups in order of appearance
482 /// in the regular expression.
483 pub fn iter(&'t self) -> SubCaptures<'t> {
484 SubCaptures { idx: 0, caps: self, }
487 /// Creates an iterator of all the capture group positions in order of
488 /// appearance in the regular expression. Positions are byte indices
489 /// in terms of the original string matched.
490 pub fn iter_pos(&'t self) -> SubCapturesPos<'t> {
491 SubCapturesPos { idx: 0, caps: self, }
494 /// Expands all instances of `$name` in `text` to the corresponding capture
497 /// `name` may be an integer corresponding to the index of the
498 /// capture group (counted by order of opening parenthesis where `0` is the
499 /// entire match) or it can be a name (consisting of letters, digits or
500 /// underscores) corresponding to a named capture group.
502 /// If `name` isn't a valid capture group (whether the name doesn't exist or
503 /// isn't a valid index), then it is replaced with the empty string.
505 /// To write a literal `$` use `$$`.
506 pub fn expand(&self, text: &str) -> String {
507 // How evil can you get?
508 // FIXME: Don't use regexes for this. It's completely unnecessary.
509 let re = Regex::new(r"(^|[^$]|\b)\$(\w+)").unwrap();
510 let text = re.replace_all(text, |&mut: refs: &Captures| -> String {
511 let pre = refs.at(1).unwrap_or("");
512 let name = refs.at(2).unwrap_or("");
514 match name.parse::<uint>() {
515 None => self.name(name).unwrap_or("").to_string(),
516 Some(i) => self.at(i).unwrap_or("").to_string(),
519 let re = Regex::new(r"\$\$").unwrap();
520 re.replace_all(text[], NoExpand("$"))
523 /// Returns the number of captured groups.
525 pub fn len(&self) -> uint { self.locs.len() / 2 }
527 /// Returns if there are no captured groups.
529 pub fn is_empty(&self) -> bool { self.len() == 0 }
532 /// An iterator over capture groups for a particular match of a regular
535 /// `'t` is the lifetime of the matched text.
537 pub struct SubCaptures<'t> {
539 caps: &'t Captures<'t>,
542 impl<'t> Iterator for SubCaptures<'t> {
545 fn next(&mut self) -> Option<&'t str> {
546 if self.idx < self.caps.len() {
548 Some(self.caps.at(self.idx - 1).unwrap_or(""))
555 /// An iterator over capture group positions for a particular match of a
556 /// regular expression.
558 /// Positions are byte indices in terms of the original string matched.
560 /// `'t` is the lifetime of the matched text.
562 pub struct SubCapturesPos<'t> {
564 caps: &'t Captures<'t>,
567 impl<'t> Iterator for SubCapturesPos<'t> {
568 type Item = Option<(uint, uint)>;
570 fn next(&mut self) -> Option<Option<(uint, uint)>> {
571 if self.idx < self.caps.len() {
573 Some(self.caps.pos(self.idx - 1))
580 /// An iterator that yields all non-overlapping capture groups matching a
581 /// particular regular expression.
583 /// The iterator stops when no more matches can be found.
585 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
586 /// of the matched string.
588 pub struct FindCaptures<'r, 't> {
591 last_match: Option<uint>,
595 impl<'r, 't> Iterator for FindCaptures<'r, 't> {
596 type Item = Captures<'t>;
598 fn next(&mut self) -> Option<Captures<'t>> {
599 if self.last_end > self.search.len() {
603 let caps = exec_slice(self.re, Submatches, self.search,
604 self.last_end, self.search.len());
606 if !has_match(&caps) {
609 (caps[0].unwrap(), caps[1].unwrap())
612 // Don't accept empty matches immediately following a match.
613 // i.e., no infinite loops please.
614 if e == s && Some(self.last_end) == self.last_match {
619 self.last_match = Some(self.last_end);
620 Captures::new(self.re, self.search, caps)
624 /// An iterator over all non-overlapping matches for a particular string.
626 /// The iterator yields a tuple of integers corresponding to the start and end
627 /// of the match. The indices are byte offsets. The iterator stops when no more
628 /// matches can be found.
630 /// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
631 /// of the matched string.
633 pub struct FindMatches<'r, 't> {
636 last_match: Option<uint>,
640 impl<'r, 't> Iterator for FindMatches<'r, 't> {
641 type Item = (uint, uint);
643 fn next(&mut self) -> Option<(uint, uint)> {
644 if self.last_end > self.search.len() {
648 let caps = exec_slice(self.re, Location, self.search,
649 self.last_end, self.search.len());
651 if !has_match(&caps) {
654 (caps[0].unwrap(), caps[1].unwrap())
657 // Don't accept empty matches immediately following a match.
658 // i.e., no infinite loops please.
659 if e == s && Some(self.last_end) == self.last_match {
664 self.last_match = Some(self.last_end);
669 fn exec(re: &Regex, which: MatchKind, input: &str) -> CaptureLocs {
670 exec_slice(re, which, input, 0, input.len())
673 fn exec_slice(re: &Regex, which: MatchKind,
674 input: &str, s: uint, e: uint) -> CaptureLocs {
676 Dynamic(ExDynamic { ref prog, .. }) => vm::run(which, prog, input, s, e),
677 Native(ExNative { ref prog, .. }) => (*prog)(which, input, s, e),
682 fn has_match(caps: &CaptureLocs) -> bool {
683 caps.len() >= 2 && caps[0].is_some() && caps[1].is_some()