1 // Copyright 2014-2015 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.
12 use std
::collections
::HashMap
;
15 use std
::str::FromStr
;
22 use exec
::{Exec, ExecNoSyncStr}
;
23 use expand
::expand_str
;
24 use re_builder
::unicode
::RegexBuilder
;
25 use re_trait
::{self, RegularExpression, Locations, SubCapturesPosIter}
;
27 /// Escapes all regular expression meta characters in `text`.
29 /// The string returned may be safely used as a literal in a regular
31 pub fn escape(text
: &str) -> String
{
35 /// Match represents a single match of a regex in a haystack.
37 /// The lifetime parameter `'t` refers to the lifetime of the matched text.
38 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
39 pub struct Match
<'t
> {
46 /// Returns the starting byte offset of the match in the haystack.
48 pub fn start(&self) -> usize {
52 /// Returns the ending byte offset of the match in the haystack.
54 pub fn end(&self) -> usize {
58 /// Returns the matched text.
60 pub fn as_str(&self) -> &'t
str {
61 &self.text
[self.start
..self.end
]
64 /// Creates a new match from the given haystack and byte offsets.
66 fn new(haystack
: &'t
str, start
: usize, end
: usize) -> Match
<'t
> {
75 impl<'t
> From
<Match
<'t
>> for &'t
str {
76 fn from(m
: Match
<'t
>) -> &'t
str {
81 /// A compiled regular expression for matching Unicode strings.
83 /// It is represented as either a sequence of bytecode instructions (dynamic)
84 /// or as a specialized Rust function (native). It can be used to search, split
85 /// or replace text. All searching is done with an implicit `.*?` at the
86 /// beginning and end of an expression. To force an expression to match the
87 /// whole string (or a prefix or a suffix), you must use an anchor like `^` or
88 /// `$` (or `\A` and `\z`).
90 /// While this crate will handle Unicode strings (whether in the regular
91 /// expression or in the search text), all positions returned are **byte
92 /// indices**. Every byte index is guaranteed to be at a Unicode code point
95 /// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a
96 /// compiled regular expression and text to search, respectively.
98 /// The only methods that allocate new strings are the string replacement
99 /// methods. All other methods (searching and splitting) return borrowed
100 /// pointers into the string given.
104 /// Find the location of a US phone number:
107 /// # use regex::Regex;
108 /// let re = Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}").unwrap();
109 /// let mat = re.find("phone: 111-222-3333").unwrap();
110 /// assert_eq!((mat.start(), mat.end()), (7, 19));
113 /// # Using the `std::str::pattern` methods with `Regex`
115 /// > **Note**: This section requires that this crate is compiled with the
116 /// > `pattern` Cargo feature enabled, which **requires nightly Rust**.
118 /// Since `Regex` implements `Pattern`, you can use regexes with methods
119 /// defined on `&str`. For example, `is_match`, `find`, `find_iter`
120 /// and `split` can be replaced with `str::contains`, `str::find`,
121 /// `str::match_indices` and `str::split`.
123 /// Here are some examples:
126 /// # use regex::Regex;
127 /// let re = Regex::new(r"\d+").unwrap();
128 /// let haystack = "a111b222c";
130 /// assert!(haystack.contains(&re));
131 /// assert_eq!(haystack.find(&re), Some(1));
132 /// assert_eq!(haystack.match_indices(&re).collect::<Vec<_>>(),
133 /// vec![(1, 4), (5, 8)]);
134 /// assert_eq!(haystack.split(&re).collect::<Vec<_>>(), vec!["a", "b", "c"]);
137 pub struct Regex(Exec
);
139 impl fmt
::Display
for Regex
{
140 /// Shows the original regular expression.
141 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
142 write
!(f
, "{}", self.as_str())
146 impl fmt
::Debug
for Regex
{
147 /// Shows the original regular expression.
148 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
149 fmt
::Display
::fmt(self, f
)
154 impl From
<Exec
> for Regex
{
155 fn from(exec
: Exec
) -> Regex
{
160 impl FromStr
for Regex
{
163 /// Attempts to parse a string into a regular expression
164 fn from_str(s
: &str) -> Result
<Regex
, Error
> {
169 /// Core regular expression methods.
171 /// Compiles a regular expression. Once compiled, it can be used repeatedly
172 /// to search, split or replace text in a string.
174 /// If an invalid expression is given, then an error is returned.
175 pub fn new(re
: &str) -> Result
<Regex
, Error
> {
176 RegexBuilder
::new(re
).build()
179 /// Returns true if and only if the regex matches the string given.
181 /// It is recommended to use this method if all you need to do is test
182 /// a match, since the underlying matching engine may be able to do less
187 /// Test if some text contains at least one word with exactly 13
188 /// Unicode word characters:
191 /// # extern crate regex; use regex::Regex;
193 /// let text = "I categorically deny having triskaidekaphobia.";
194 /// assert!(Regex::new(r"\b\w{13}\b").unwrap().is_match(text));
197 pub fn is_match(&self, text
: &str) -> bool
{
198 self.is_match_at(text
, 0)
201 /// Returns the start and end byte range of the leftmost-first match in
202 /// `text`. If no match exists, then `None` is returned.
204 /// Note that this should only be used if you want to discover the position
205 /// of the match. Testing the existence of a match is faster if you use
210 /// Find the start and end location of the first word with exactly 13
211 /// Unicode word characters:
214 /// # extern crate regex; use regex::Regex;
216 /// let text = "I categorically deny having triskaidekaphobia.";
217 /// let mat = Regex::new(r"\b\w{13}\b").unwrap().find(text).unwrap();
218 /// assert_eq!(mat.start(), 2);
219 /// assert_eq!(mat.end(), 15);
222 pub fn find
<'t
>(&self, text
: &'t
str) -> Option
<Match
<'t
>> {
223 self.find_at(text
, 0)
226 /// Returns an iterator for each successive non-overlapping match in
227 /// `text`, returning the start and end byte indices with respect to
232 /// Find the start and end location of every word with exactly 13 Unicode
236 /// # extern crate regex; use regex::Regex;
238 /// let text = "Retroactively relinquishing remunerations is reprehensible.";
239 /// for mat in Regex::new(r"\b\w{13}\b").unwrap().find_iter(text) {
240 /// println!("{:?}", mat);
244 pub fn find_iter
<'r
, 't
>(&'r
self, text
: &'t
str) -> Matches
<'r
, 't
> {
245 Matches(self.0.searcher_str().find_iter(text
))
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.
252 /// You should only use `captures` if you need access to the location of
253 /// capturing group matches. Otherwise, `find` is faster for discovering
254 /// the location of the overall match.
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
264 /// # extern crate regex; use regex::Regex;
266 /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap();
267 /// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
268 /// let caps = re.captures(text).unwrap();
269 /// assert_eq!(caps.get(1).unwrap().as_str(), "Citizen Kane");
270 /// assert_eq!(caps.get(2).unwrap().as_str(), "1941");
271 /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)");
272 /// // You can also access the groups by index using the Index notation.
273 /// // Note that this will panic on an invalid index.
274 /// assert_eq!(&caps[1], "Citizen Kane");
275 /// assert_eq!(&caps[2], "1941");
276 /// assert_eq!(&caps[0], "'Citizen Kane' (1941)");
280 /// Note that the full match is at capture group `0`. Each subsequent
281 /// capture group is indexed by the order of its opening `(`.
283 /// We can make this example a bit clearer by using *named* capture groups:
286 /// # extern crate regex; use regex::Regex;
288 /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)")
290 /// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
291 /// let caps = re.captures(text).unwrap();
292 /// assert_eq!(&caps["title"], "Citizen Kane");
293 /// assert_eq!(&caps["year"], "1941");
294 /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)");
295 /// // You can also access the groups by name using the Index notation.
296 /// // Note that this will panic on an invalid group name.
297 /// assert_eq!(&caps["title"], "Citizen Kane");
298 /// assert_eq!(&caps["year"], "1941");
299 /// assert_eq!(&caps[0], "'Citizen Kane' (1941)");
304 /// Here we name the capture groups, which we can access with the `name`
305 /// method or the `Index` notation with a `&str`. Note that the named
306 /// capture groups are still accessible with `get` or the `Index` notation
309 /// The `0`th capture group is always unnamed, so it must always be
310 /// accessed with `get(0)` or `[0]`.
311 pub fn captures
<'t
>(&self, text
: &'t
str) -> Option
<Captures
<'t
>> {
312 let mut locs
= self.locations();
313 self.read_captures_at(&mut locs
, text
, 0).map(|_
| Captures
{
316 named_groups
: self.0.capture_name_idx().clone(),
320 /// Returns an iterator over all the non-overlapping capture groups matched
321 /// in `text`. This is operationally the same as `find_iter`, except it
322 /// yields information about capturing group matches.
326 /// We can use this to find all movie titles and their release years in
327 /// some text, where the movie is formatted like "'Title' (xxxx)":
330 /// # extern crate regex; use regex::Regex;
332 /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)")
334 /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931).";
335 /// for caps in re.captures_iter(text) {
336 /// println!("Movie: {:?}, Released: {:?}",
337 /// &caps["title"], &caps["year"]);
340 /// // Movie: Citizen Kane, Released: 1941
341 /// // Movie: The Wizard of Oz, Released: 1939
342 /// // Movie: M, Released: 1931
345 pub fn captures_iter
<'r
, 't
>(
348 ) -> CaptureMatches
<'r
, 't
> {
349 CaptureMatches(self.0.searcher_str().captures_iter(text
))
352 /// Returns an iterator of substrings of `text` delimited by a match of the
353 /// regular expression. Namely, each element of the iterator corresponds to
354 /// text that *isn't* matched by the regular expression.
356 /// This method will *not* copy the text given.
360 /// To split a string delimited by arbitrary amounts of spaces or tabs:
363 /// # extern crate regex; use regex::Regex;
365 /// let re = Regex::new(r"[ \t]+").unwrap();
366 /// let fields: Vec<&str> = re.split("a b \t c\td e").collect();
367 /// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]);
370 pub fn split
<'r
, 't
>(&'r
self, text
: &'t
str) -> Split
<'r
, 't
> {
372 finder
: self.find_iter(text
),
377 /// Returns an iterator of at most `limit` substrings of `text` delimited
378 /// by a match of the regular expression. (A `limit` of `0` will return no
379 /// substrings.) Namely, each element of the iterator corresponds to text
380 /// that *isn't* matched by the regular expression. The remainder of the
381 /// string that is not split will be the last element in the iterator.
383 /// This method will *not* copy the text given.
387 /// Get the first two words in some text:
390 /// # extern crate regex; use regex::Regex;
392 /// let re = Regex::new(r"\W+").unwrap();
393 /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect();
394 /// assert_eq!(fields, vec!("Hey", "How", "are you?"));
397 pub fn splitn
<'r
, 't
>(&'r
self, text
: &'t
str, limit
: usize)
400 splits
: self.split(text
),
405 /// Replaces the leftmost-first match with the replacement provided.
406 /// The replacement can be a regular string (where `$N` and `$name` are
407 /// expanded to match capture groups) or a function that takes the matches'
408 /// `Captures` and returns the replaced string.
410 /// If no match is found, then a copy of the string is returned unchanged.
412 /// # Replacement string syntax
414 /// All instances of `$name` in the replacement text is replaced with the
415 /// corresponding capture group `name`.
417 /// `name` may be an integer corresponding to the index of the
418 /// capture group (counted by order of opening parenthesis where `0` is the
419 /// entire match) or it can be a name (consisting of letters, digits or
420 /// underscores) corresponding to a named capture group.
422 /// If `name` isn't a valid capture group (whether the name doesn't exist
423 /// or isn't a valid index), then it is replaced with the empty string.
425 /// The longest possible name is used. e.g., `$1a` looks up the capture
426 /// group named `1a` and not the capture group at index `1`. To exert more
427 /// precise control over the name, use braces, e.g., `${1}a`.
429 /// To write a literal `$` use `$$`.
433 /// Note that this function is polymorphic with respect to the replacement.
434 /// In typical usage, this can just be a normal string:
437 /// # extern crate regex; use regex::Regex;
439 /// let re = Regex::new("[^01]+").unwrap();
440 /// assert_eq!(re.replace("1078910", ""), "1010");
444 /// But anything satisfying the `Replacer` trait will work. For example,
445 /// a closure of type `|&Captures| -> String` provides direct access to the
446 /// captures corresponding to a match. This allows one to access
447 /// capturing group matches easily:
450 /// # extern crate regex; use regex::Regex;
451 /// # use regex::Captures; fn main() {
452 /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap();
453 /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| {
454 /// format!("{} {}", &caps[2], &caps[1])
456 /// assert_eq!(result, "Bruce Springsteen");
460 /// But this is a bit cumbersome to use all the time. Instead, a simple
461 /// syntax is supported that expands `$name` into the corresponding capture
462 /// group. Here's the last example, but using this expansion technique
463 /// with named capture groups:
466 /// # extern crate regex; use regex::Regex;
468 /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap();
469 /// let result = re.replace("Springsteen, Bruce", "$first $last");
470 /// assert_eq!(result, "Bruce Springsteen");
474 /// Note that using `$2` instead of `$first` or `$1` instead of `$last`
475 /// would produce the same result. To write a literal `$` use `$$`.
477 /// Sometimes the replacement string requires use of curly braces to
478 /// delineate a capture group replacement and surrounding literal text.
479 /// For example, if we wanted to join two words together with an
483 /// # extern crate regex; use regex::Regex;
485 /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap();
486 /// let result = re.replace("deep fried", "${first}_$second");
487 /// assert_eq!(result, "deep_fried");
491 /// Without the curly braces, the capture group name `first_` would be
492 /// used, and since it doesn't exist, it would be replaced with the empty
495 /// Finally, sometimes you just want to replace a literal string with no
496 /// regard for capturing group expansion. This can be done by wrapping a
497 /// byte string with `NoExpand`:
500 /// # extern crate regex; use regex::Regex;
502 /// use regex::NoExpand;
504 /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap();
505 /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last"));
506 /// assert_eq!(result, "$2 $last");
509 pub fn replace
<'t
, R
: Replacer
>(
514 self.replacen(text
, 1, rep
)
517 /// Replaces all non-overlapping matches in `text` with the replacement
518 /// provided. This is the same as calling `replacen` with `limit` set to
521 /// See the documentation for `replace` for details on how to access
522 /// capturing group matches in the replacement string.
523 pub fn replace_all
<'t
, R
: Replacer
>(
528 self.replacen(text
, 0, rep
)
531 /// Replaces at most `limit` non-overlapping matches in `text` with the
532 /// replacement provided. If `limit` is 0, then all non-overlapping matches
535 /// See the documentation for `replace` for details on how to access
536 /// capturing group matches in the replacement string.
537 pub fn replacen
<'t
, R
: Replacer
>(
543 // If we know that the replacement doesn't have any capture expansions,
544 // then we can fast path. The fast path can make a tremendous
547 // 1) We use `find_iter` instead of `captures_iter`. Not asking for
548 // captures generally makes the regex engines faster.
549 // 2) We don't need to look up all of the capture groups and do
550 // replacements inside the replacement string. We just push it
551 // at each match and be done with it.
552 if let Some(rep
) = rep
.no_expansion() {
553 let mut it
= self.find_iter(text
).enumerate().peekable();
554 if it
.peek().is_none() {
555 return Cow
::Borrowed(text
);
557 let mut new
= String
::with_capacity(text
.len());
558 let mut last_match
= 0;
560 if limit
> 0 && i
>= limit
{
563 new
.push_str(&text
[last_match
..m
.start()]);
565 last_match
= m
.end();
567 new
.push_str(&text
[last_match
..]);
568 return Cow
::Owned(new
);
571 // The slower path, which we use if the replacement needs access to
573 let mut it
= self.captures_iter(text
).enumerate().peekable();
574 if it
.peek().is_none() {
575 return Cow
::Borrowed(text
);
577 let mut new
= String
::with_capacity(text
.len());
578 let mut last_match
= 0;
580 if limit
> 0 && i
>= limit
{
583 // unwrap on 0 is OK because captures only reports matches
584 let m
= cap
.get(0).unwrap();
585 new
.push_str(&text
[last_match
..m
.start()]);
586 rep
.replace_append(&cap
, &mut new
);
587 last_match
= m
.end();
589 new
.push_str(&text
[last_match
..]);
594 /// Advanced or "lower level" search methods.
596 /// Returns the end location of a match in the text given.
598 /// This method may have the same performance characteristics as
599 /// `is_match`, except it provides an end location for a match. In
600 /// particular, the location returned *may be shorter* than the proper end
601 /// of the leftmost-first match.
605 /// Typically, `a+` would match the entire first sequence of `a` in some
606 /// text, but `shortest_match` can give up as soon as it sees the first
610 /// # extern crate regex; use regex::Regex;
612 /// let text = "aaaaa";
613 /// let pos = Regex::new(r"a+").unwrap().shortest_match(text);
614 /// assert_eq!(pos, Some(1));
617 pub fn shortest_match(&self, text
: &str) -> Option
<usize> {
618 self.shortest_match_at(text
, 0)
621 /// Returns the same as shortest_match, but starts the search at the given
624 /// The significance of the starting point is that it takes the surrounding
625 /// context into consideration. For example, the `\A` anchor can only
626 /// match when `start == 0`.
628 pub fn shortest_match_at(
633 self.0.searcher_str().shortest_match_at(text
, start
)
636 /// Returns the same as is_match, but starts the search at the given
639 /// The significance of the starting point is that it takes the surrounding
640 /// context into consideration. For example, the `\A` anchor can only
641 /// match when `start == 0`.
643 pub fn is_match_at(&self, text
: &str, start
: usize) -> bool
{
644 self.shortest_match_at(text
, start
).is_some()
647 /// Returns the same as find, but starts the search at the given
650 /// The significance of the starting point is that it takes the surrounding
651 /// context into consideration. For example, the `\A` anchor can only
652 /// match when `start == 0`.
658 ) -> Option
<Match
<'t
>> {
659 self.0.searcher_str().find_at(text
, start
).map(|(s
, e
)| {
660 Match
::new(text
, s
, e
)
664 /// Returns the same as captures, but starts the search at the given
665 /// offset and populates the capture locations given.
667 /// The significance of the starting point is that it takes the surrounding
668 /// context into consideration. For example, the `\A` anchor can only
669 /// match when `start == 0`.
671 pub fn read_captures_at
<'t
>(
673 locs
: &mut Locations
,
676 ) -> Option
<Match
<'t
>> {
679 .read_captures_at(locs
, text
, start
)
680 .map(|(s
, e
)| Match
::new(text
, s
, e
))
684 /// Auxiliary methods.
686 /// Returns the original string of this regex.
687 pub fn as_str(&self) -> &str {
688 &self.0.regex_strings()[0]
691 /// Returns an iterator over the capture names.
692 pub fn capture_names(&self) -> CaptureNames
{
693 CaptureNames(self.0.capture_names().iter())
696 /// Returns the number of captures.
697 pub fn captures_len(&self) -> usize {
698 self.0.capture_names().len()
701 /// Returns an empty set of locations that can be reused in multiple calls
702 /// to `read_captures`.
704 pub fn locations(&self) -> Locations
{
705 self.0.searcher_str().locations()
709 /// An iterator over the names of all possible captures.
711 /// `None` indicates an unnamed capture; the first element (capture 0, the
712 /// whole matched region) is always unnamed.
714 /// `'r` is the lifetime of the compiled regular expression.
715 pub struct CaptureNames
<'r
>(::std
::slice
::Iter
<'r
, Option
<String
>>);
717 impl<'r
> Iterator
for CaptureNames
<'r
> {
718 type Item
= Option
<&'r
str>;
720 fn next(&mut self) -> Option
<Option
<&'r
str>> {
724 .map(|slot
| slot
.as_ref().map(|name
| name
.as_ref()))
727 fn size_hint(&self) -> (usize, Option
<usize>) {
732 /// Yields all substrings delimited by a regular expression match.
734 /// `'r` is the lifetime of the compiled regular expression and `'t` is the
735 /// lifetime of the string being split.
736 pub struct Split
<'r
, 't
> {
737 finder
: Matches
<'r
, 't
>,
741 impl<'r
, 't
> Iterator
for Split
<'r
, 't
> {
744 fn next(&mut self) -> Option
<&'t
str> {
745 let text
= self.finder
.0.text();
746 match self.finder
.next() {
748 if self.last
>= text
.len() {
751 let s
= &text
[self.last
..];
752 self.last
= text
.len();
757 let matched
= &text
[self.last
..m
.start()];
765 /// Yields at most `N` substrings delimited by a regular expression match.
767 /// The last substring will be whatever remains after splitting.
769 /// `'r` is the lifetime of the compiled regular expression and `'t` is the
770 /// lifetime of the string being split.
771 pub struct SplitN
<'r
, 't
> {
772 splits
: Split
<'r
, 't
>,
776 impl<'r
, 't
> Iterator
for SplitN
<'r
, 't
> {
779 fn next(&mut self) -> Option
<&'t
str> {
785 let text
= self.splits
.finder
.0.text();
786 Some(&text
[self.splits
.last
..])
793 /// Captures represents a group of captured strings for a single match.
795 /// The 0th capture always corresponds to the entire match. Each subsequent
796 /// index corresponds to the next capture group in the regex. If a capture
797 /// group is named, then the matched string is *also* available via the `name`
798 /// method. (Note that the 0th capture is always unnamed and so must be
799 /// accessed with the `get` method.)
801 /// Positions returned from a capture group are always byte indices.
803 /// `'t` is the lifetime of the matched text.
804 pub struct Captures
<'t
> {
807 named_groups
: Arc
<HashMap
<String
, usize>>,
810 impl<'t
> Captures
<'t
> {
811 /// Returns the match associated with the capture group at index `i`. If
812 /// `i` does not correspond to a capture group, or if the capture group
813 /// did not participate in the match, then `None` is returned.
817 /// Get the text of the match with a default of an empty string if this
818 /// group didn't participate in the match:
821 /// # use regex::Regex;
822 /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap();
823 /// let caps = re.captures("abc123").unwrap();
825 /// let text1 = caps.get(1).map_or("", |m| m.as_str());
826 /// let text2 = caps.get(2).map_or("", |m| m.as_str());
827 /// assert_eq!(text1, "123");
828 /// assert_eq!(text2, "");
830 pub fn get(&self, i
: usize) -> Option
<Match
<'t
>> {
831 self.locs
.pos(i
).map(|(s
, e
)| Match
::new(self.text
, s
, e
))
834 /// Returns the match for the capture group named `name`. If `name` isn't a
835 /// valid capture group or didn't match anything, then `None` is returned.
836 pub fn name(&self, name
: &str) -> Option
<Match
<'t
>> {
837 self.named_groups
.get(name
).and_then(|&i
| self.get(i
))
840 /// An iterator that yields all capturing matches in the order in which
841 /// they appear in the regex. If a particular capture group didn't
842 /// participate in the match, then `None` is yielded for that capture.
844 /// The first match always corresponds to the overall match of the regex.
845 pub fn iter
<'c
>(&'c
self) -> SubCaptureMatches
<'c
, 't
> {
848 it
: self.locs
.iter(),
852 /// Expands all instances of `$name` in `replacement` to the corresponding
853 /// capture group `name`, and writes them to the `dst` buffer given.
855 /// `name` may be an integer corresponding to the index of the
856 /// capture group (counted by order of opening parenthesis where `0` is the
857 /// entire match) or it can be a name (consisting of letters, digits or
858 /// underscores) corresponding to a named capture group.
860 /// If `name` isn't a valid capture group (whether the name doesn't exist
861 /// or isn't a valid index), then it is replaced with the empty string.
863 /// The longest possible name is used. e.g., `$1a` looks up the capture
864 /// group named `1a` and not the capture group at index `1`. To exert more
865 /// precise control over the name, use braces, e.g., `${1}a`.
867 /// To write a literal `$` use `$$`.
868 pub fn expand(&self, replacement
: &str, dst
: &mut String
) {
869 expand_str(self, replacement
, dst
)
872 /// Returns the number of captured groups.
874 /// This is always at least `1`, since every regex has at least one capture
875 /// group that corresponds to the full match.
877 pub fn len(&self) -> usize {
882 impl<'t
> fmt
::Debug
for Captures
<'t
> {
883 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
884 f
.debug_tuple("Captures").field(&CapturesDebug(self)).finish()
888 struct CapturesDebug
<'c
, 't
: 'c
>(&'c Captures
<'t
>);
890 impl<'c
, 't
> fmt
::Debug
for CapturesDebug
<'c
, 't
> {
891 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
892 // We'd like to show something nice here, even if it means an
893 // allocation to build a reverse index.
894 let slot_to_name
: HashMap
<&usize, &String
> =
895 self.0.named_groups
.iter().map(|(a
, b
)| (b
, a
)).collect();
896 let mut map
= f
.debug_map();
897 for (slot
, m
) in self.0.locs
.iter().enumerate() {
898 let m
= m
.map(|(s
, e
)| &self.0.text
[s
..e
]);
899 if let Some(name
) = slot_to_name
.get(&slot
) {
900 map
.entry(&name
, &m
);
902 map
.entry(&slot
, &m
);
909 /// Get a group by index.
911 /// `'t` is the lifetime of the matched text.
913 /// The text can't outlive the `Captures` object if this method is
914 /// used, because of how `Index` is defined (normally `a[i]` is part
915 /// of `a` and can't outlive it); to do that, use `get()` instead.
919 /// If there is no group at the given index.
920 impl<'t
> Index
<usize> for Captures
<'t
> {
923 fn index(&self, i
: usize) -> &str {
924 self.get(i
).map(|m
| m
.as_str())
925 .unwrap_or_else(|| panic
!("no group at index '{}'", i
))
929 /// Get a group by name.
931 /// `'t` is the lifetime of the matched text and `'i` is the lifetime
932 /// of the group name (the index).
934 /// The text can't outlive the `Captures` object if this method is
935 /// used, because of how `Index` is defined (normally `a[i]` is part
936 /// of `a` and can't outlive it); to do that, use `name` instead.
940 /// If there is no group named by the given value.
941 impl<'t
, 'i
> Index
<&'i
str> for Captures
<'t
> {
944 fn index
<'a
>(&'a
self, name
: &'i
str) -> &'a
str {
945 self.name(name
).map(|m
| m
.as_str())
946 .unwrap_or_else(|| panic
!("no group named '{}'", name
))
950 /// An iterator that yields all capturing matches in the order in which they
951 /// appear in the regex.
953 /// If a particular capture group didn't participate in the match, then `None`
954 /// is yielded for that capture. The first match always corresponds to the
955 /// overall match of the regex.
957 /// The lifetime `'c` corresponds to the lifetime of the `Captures` value, and
958 /// the lifetime `'t` corresponds to the originally matched text.
959 pub struct SubCaptureMatches
<'c
, 't
: 'c
> {
960 caps
: &'c Captures
<'t
>,
961 it
: SubCapturesPosIter
<'c
>,
964 impl<'c
, 't
> Iterator
for SubCaptureMatches
<'c
, 't
> {
965 type Item
= Option
<Match
<'t
>>;
967 fn next(&mut self) -> Option
<Option
<Match
<'t
>>> {
969 .map(|cap
| cap
.map(|(s
, e
)| Match
::new(self.caps
.text
, s
, e
)))
973 /// An iterator that yields all non-overlapping capture groups matching a
974 /// particular regular expression.
976 /// The iterator stops when no more matches can be found.
978 /// `'r` is the lifetime of the compiled regular expression and `'t` is the
979 /// lifetime of the matched string.
980 pub struct CaptureMatches
<'r
, 't
>(re_trait
::CaptureMatches
<'t
, ExecNoSyncStr
<'r
>>);
982 impl<'r
, 't
> Iterator
for CaptureMatches
<'r
, 't
> {
983 type Item
= Captures
<'t
>;
985 fn next(&mut self) -> Option
<Captures
<'t
>> {
986 self.0.next().map(|locs
| Captures
{
989 named_groups
: self.0.regex().capture_name_idx().clone(),
994 /// An iterator over all non-overlapping matches for a particular string.
996 /// The iterator yields a `Match` value. The iterator stops when no more
997 /// matches can be found.
999 /// `'r` is the lifetime of the compiled regular expression and `'t` is the
1000 /// lifetime of the matched string.
1001 pub struct Matches
<'r
, 't
>(re_trait
::Matches
<'t
, ExecNoSyncStr
<'r
>>);
1003 impl<'r
, 't
> Iterator
for Matches
<'r
, 't
> {
1004 type Item
= Match
<'t
>;
1006 fn next(&mut self) -> Option
<Match
<'t
>> {
1007 let text
= self.0.text();
1008 self.0.next().map(|(s
, e
)| Match
::new(text
, s
, e
))
1012 /// Replacer describes types that can be used to replace matches in a string.
1014 /// In general, users of this crate shouldn't need to implement this trait,
1015 /// since implementations are already provided for `&str` and
1016 /// `FnMut(&Captures) -> String`, which covers most use cases.
1017 pub trait Replacer
{
1018 /// Appends text to `dst` to replace the current match.
1020 /// The current match is represented by `caps`, which is guaranteed to
1021 /// have a match at capture group `0`.
1023 /// For example, a no-op replacement would be
1024 /// `dst.extend(caps.get(0).unwrap().as_str())`.
1025 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
);
1027 /// Return a fixed unchanging replacement string.
1029 /// When doing replacements, if access to `Captures` is not needed (e.g.,
1030 /// the replacement byte string does not need `$` expansion), then it can
1031 /// be beneficial to avoid finding sub-captures.
1033 /// In general, this is called once for every call to `replacen`.
1034 fn no_expansion
<'r
>(&'r
mut self) -> Option
<Cow
<'r
, str>> {
1039 impl<'a
> Replacer
for &'a
str {
1040 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
) {
1041 caps
.expand(*self, dst
);
1044 fn no_expansion(&mut self) -> Option
<Cow
<str>> {
1045 match memchr(b'$'
, self.as_bytes()) {
1047 None
=> Some(Cow
::Borrowed(*self)),
1052 impl<F
> Replacer
for F
where F
: FnMut(&Captures
) -> String
{
1053 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
) {
1054 dst
.push_str(&(*self)(caps
));
1058 /// `NoExpand` indicates literal string replacement.
1060 /// It can be used with `replace` and `replace_all` to do a literal string
1061 /// replacement without expanding `$name` to their corresponding capture
1062 /// groups. This can be both convenient (to avoid escaping `$`, for example)
1063 /// and performant (since capture groups don't need to be found).
1065 /// `'t` is the lifetime of the literal text.
1066 pub struct NoExpand
<'t
>(pub &'t
str);
1068 impl<'t
> Replacer
for NoExpand
<'t
> {
1069 fn replace_append(&mut self, _
: &Captures
, dst
: &mut String
) {
1070 dst
.push_str(self.0);
1073 fn no_expansion(&mut self) -> Option
<Cow
<str>> {
1074 Some(Cow
::Borrowed(self.0))