2 use std
::collections
::HashMap
;
4 use std
::iter
::FusedIterator
;
5 use std
::ops
::{Index, Range}
;
9 use find_byte
::find_byte
;
13 use exec
::{Exec, ExecNoSyncStr}
;
14 use expand
::expand_str
;
15 use re_builder
::unicode
::RegexBuilder
;
16 use re_trait
::{self, RegularExpression, SubCapturesPosIter}
;
18 /// Escapes all regular expression meta characters in `text`.
20 /// The string returned may be safely used as a literal in a regular
22 pub fn escape(text
: &str) -> String
{
26 /// Match represents a single match of a regex in a haystack.
28 /// The lifetime parameter `'t` refers to the lifetime of the matched text.
29 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
30 pub struct Match
<'t
> {
37 /// Returns the starting byte offset of the match in the haystack.
39 pub fn start(&self) -> usize {
43 /// Returns the ending byte offset of the match in the haystack.
45 pub fn end(&self) -> usize {
49 /// Returns the range over the starting and ending byte offsets of the
50 /// match in the haystack.
52 pub fn range(&self) -> Range
<usize> {
56 /// Returns the matched text.
58 pub fn as_str(&self) -> &'t
str {
59 &self.text
[self.range()]
62 /// Creates a new match from the given haystack and byte offsets.
64 fn new(haystack
: &'t
str, start
: usize, end
: usize) -> Match
<'t
> {
65 Match { text: haystack, start: start, end: end }
69 impl<'t
> From
<Match
<'t
>> for &'t
str {
70 fn from(m
: Match
<'t
>) -> &'t
str {
75 impl<'t
> From
<Match
<'t
>> for Range
<usize> {
76 fn from(m
: Match
<'t
>) -> Range
<usize> {
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 there is a match for the regex in the
182 /// It is recommended to use this method if all you need to do is test
183 /// a match, since the underlying matching engine may be able to do less
188 /// Test if some text contains at least one word with exactly 13
189 /// Unicode word characters:
192 /// # extern crate regex; use regex::Regex;
194 /// let text = "I categorically deny having triskaidekaphobia.";
195 /// assert!(Regex::new(r"\b\w{13}\b").unwrap().is_match(text));
198 pub fn is_match(&self, text
: &str) -> bool
{
199 self.is_match_at(text
, 0)
202 /// Returns the start and end byte range of the leftmost-first match in
203 /// `text`. If no match exists, then `None` is returned.
205 /// Note that this should only be used if you want to discover the position
206 /// of the match. Testing the existence of a match is faster if you use
211 /// Find the start and end location of the first word with exactly 13
212 /// Unicode word characters:
215 /// # extern crate regex; use regex::Regex;
217 /// let text = "I categorically deny having triskaidekaphobia.";
218 /// let mat = Regex::new(r"\b\w{13}\b").unwrap().find(text).unwrap();
219 /// assert_eq!(mat.start(), 2);
220 /// assert_eq!(mat.end(), 15);
223 pub fn find
<'t
>(&self, text
: &'t
str) -> Option
<Match
<'t
>> {
224 self.find_at(text
, 0)
227 /// Returns an iterator for each successive non-overlapping match in
228 /// `text`, returning the start and end byte indices with respect to
233 /// Find the start and end location of every word with exactly 13 Unicode
237 /// # extern crate regex; use regex::Regex;
239 /// let text = "Retroactively relinquishing remunerations is reprehensible.";
240 /// for mat in Regex::new(r"\b\w{13}\b").unwrap().find_iter(text) {
241 /// println!("{:?}", mat);
245 pub fn find_iter
<'r
, 't
>(&'r
self, text
: &'t
str) -> Matches
<'r
, 't
> {
246 Matches(self.0.searcher_str().find_iter(text
))
249 /// Returns the capture groups corresponding to the leftmost-first
250 /// match in `text`. Capture group `0` always corresponds to the entire
251 /// match. If no match is found, then `None` is returned.
253 /// You should only use `captures` if you need access to the location of
254 /// capturing group matches. Otherwise, `find` is faster for discovering
255 /// the location of the overall match.
259 /// Say you have some text with movie names and their release years,
260 /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text
261 /// looking like that, while also extracting the movie name and its release
265 /// # extern crate regex; use regex::Regex;
267 /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap();
268 /// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
269 /// let caps = re.captures(text).unwrap();
270 /// assert_eq!(caps.get(1).unwrap().as_str(), "Citizen Kane");
271 /// assert_eq!(caps.get(2).unwrap().as_str(), "1941");
272 /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)");
273 /// // You can also access the groups by index using the Index notation.
274 /// // Note that this will panic on an invalid index.
275 /// assert_eq!(&caps[1], "Citizen Kane");
276 /// assert_eq!(&caps[2], "1941");
277 /// assert_eq!(&caps[0], "'Citizen Kane' (1941)");
281 /// Note that the full match is at capture group `0`. Each subsequent
282 /// capture group is indexed by the order of its opening `(`.
284 /// We can make this example a bit clearer by using *named* capture groups:
287 /// # extern crate regex; use regex::Regex;
289 /// let re = Regex::new(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").unwrap().as_str(), "Citizen Kane");
294 /// assert_eq!(caps.name("year").unwrap().as_str(), "1941");
295 /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)");
296 /// // You can also access the groups by name using the Index notation.
297 /// // Note that this will panic on an invalid group name.
298 /// assert_eq!(&caps["title"], "Citizen Kane");
299 /// assert_eq!(&caps["year"], "1941");
300 /// assert_eq!(&caps[0], "'Citizen Kane' (1941)");
305 /// Here we name the capture groups, which we can access with the `name`
306 /// method or the `Index` notation with a `&str`. Note that the named
307 /// capture groups are still accessible with `get` or the `Index` notation
310 /// The `0`th capture group is always unnamed, so it must always be
311 /// accessed with `get(0)` or `[0]`.
312 pub fn captures
<'t
>(&self, text
: &'t
str) -> Option
<Captures
<'t
>> {
313 let mut locs
= self.capture_locations();
314 self.captures_read_at(&mut locs
, text
, 0).map(move |_
| Captures
{
317 named_groups
: self.0.capture_name_idx().clone(),
321 /// Returns an iterator over all the non-overlapping capture groups matched
322 /// in `text`. This is operationally the same as `find_iter`, except it
323 /// yields information about capturing group matches.
327 /// We can use this to find all movie titles and their release years in
328 /// some text, where the movie is formatted like "'Title' (xxxx)":
331 /// # extern crate regex; use regex::Regex;
333 /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)")
335 /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931).";
336 /// for caps in re.captures_iter(text) {
337 /// println!("Movie: {:?}, Released: {:?}",
338 /// &caps["title"], &caps["year"]);
341 /// // Movie: Citizen Kane, Released: 1941
342 /// // Movie: The Wizard of Oz, Released: 1939
343 /// // Movie: M, Released: 1931
346 pub fn captures_iter
<'r
, 't
>(
349 ) -> CaptureMatches
<'r
, 't
> {
350 CaptureMatches(self.0.searcher_str().captures_iter(text
))
353 /// Returns an iterator of substrings of `text` delimited by a match of the
354 /// regular expression. Namely, each element of the iterator corresponds to
355 /// text that *isn't* matched by the regular expression.
357 /// This method will *not* copy the text given.
361 /// To split a string delimited by arbitrary amounts of spaces or tabs:
364 /// # extern crate regex; use regex::Regex;
366 /// let re = Regex::new(r"[ \t]+").unwrap();
367 /// let fields: Vec<&str> = re.split("a b \t c\td e").collect();
368 /// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]);
371 pub fn split
<'r
, 't
>(&'r
self, text
: &'t
str) -> Split
<'r
, 't
> {
372 Split { finder: self.find_iter(text), last: 0 }
375 /// Returns an iterator of at most `limit` substrings of `text` delimited
376 /// by a match of the regular expression. (A `limit` of `0` will return no
377 /// substrings.) Namely, each element of the iterator corresponds to text
378 /// that *isn't* matched by the regular expression. The remainder of the
379 /// string that is not split will be the last element in the iterator.
381 /// This method will *not* copy the text given.
385 /// Get the first two words in some text:
388 /// # extern crate regex; use regex::Regex;
390 /// let re = Regex::new(r"\W+").unwrap();
391 /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect();
392 /// assert_eq!(fields, vec!("Hey", "How", "are you?"));
395 pub fn splitn
<'r
, 't
>(
399 ) -> SplitN
<'r
, 't
> {
400 SplitN { splits: self.split(text), n: limit }
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.
408 /// If no match is found, then a copy of the string is returned unchanged.
410 /// # Replacement string syntax
412 /// All instances of `$name` in the replacement text is replaced with the
413 /// corresponding capture group `name`.
415 /// `name` may be an integer corresponding to the index of the
416 /// capture group (counted by order of opening parenthesis where `0` is the
417 /// entire match) or it can be a name (consisting of letters, digits or
418 /// underscores) corresponding to a named capture group.
420 /// If `name` isn't a valid capture group (whether the name doesn't exist
421 /// or isn't a valid index), then it is replaced with the empty string.
423 /// The longest possible name is used. e.g., `$1a` looks up the capture
424 /// group named `1a` and not the capture group at index `1`. To exert more
425 /// precise control over the name, use braces, e.g., `${1}a`.
427 /// To write a literal `$` use `$$`.
431 /// Note that this function is polymorphic with respect to the replacement.
432 /// In typical usage, this can just be a normal string:
435 /// # extern crate regex; use regex::Regex;
437 /// let re = Regex::new("[^01]+").unwrap();
438 /// assert_eq!(re.replace("1078910", ""), "1010");
442 /// But anything satisfying the `Replacer` trait will work. For example,
443 /// a closure of type `|&Captures| -> String` provides direct access to the
444 /// captures corresponding to a match. This allows one to access
445 /// capturing group matches easily:
448 /// # extern crate regex; use regex::Regex;
449 /// # use regex::Captures; fn main() {
450 /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap();
451 /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| {
452 /// format!("{} {}", &caps[2], &caps[1])
454 /// assert_eq!(result, "Bruce Springsteen");
458 /// But this is a bit cumbersome to use all the time. Instead, a simple
459 /// syntax is supported that expands `$name` into the corresponding capture
460 /// group. Here's the last example, but using this expansion technique
461 /// with named capture groups:
464 /// # extern crate regex; use regex::Regex;
466 /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap();
467 /// let result = re.replace("Springsteen, Bruce", "$first $last");
468 /// assert_eq!(result, "Bruce Springsteen");
472 /// Note that using `$2` instead of `$first` or `$1` instead of `$last`
473 /// would produce the same result. To write a literal `$` use `$$`.
475 /// Sometimes the replacement string requires use of curly braces to
476 /// delineate a capture group replacement and surrounding literal text.
477 /// For example, if we wanted to join two words together with an
481 /// # extern crate regex; use regex::Regex;
483 /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap();
484 /// let result = re.replace("deep fried", "${first}_$second");
485 /// assert_eq!(result, "deep_fried");
489 /// Without the curly braces, the capture group name `first_` would be
490 /// used, and since it doesn't exist, it would be replaced with the empty
493 /// Finally, sometimes you just want to replace a literal string with no
494 /// regard for capturing group expansion. This can be done by wrapping a
495 /// byte string with `NoExpand`:
498 /// # extern crate regex; use regex::Regex;
500 /// use regex::NoExpand;
502 /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap();
503 /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last"));
504 /// assert_eq!(result, "$2 $last");
507 pub fn replace
<'t
, R
: Replacer
>(
512 self.replacen(text
, 1, rep
)
515 /// Replaces all non-overlapping matches in `text` with the replacement
516 /// provided. This is the same as calling `replacen` with `limit` set to
519 /// See the documentation for `replace` for details on how to access
520 /// capturing group matches in the replacement string.
521 pub fn replace_all
<'t
, R
: Replacer
>(
526 self.replacen(text
, 0, rep
)
529 /// Replaces at most `limit` non-overlapping matches in `text` with the
530 /// replacement provided. If `limit` is 0, then all non-overlapping matches
533 /// See the documentation for `replace` for details on how to access
534 /// capturing group matches in the replacement string.
535 pub fn replacen
<'t
, R
: Replacer
>(
541 // If we know that the replacement doesn't have any capture expansions,
542 // then we can fast path. The fast path can make a tremendous
545 // 1) We use `find_iter` instead of `captures_iter`. Not asking for
546 // captures generally makes the regex engines faster.
547 // 2) We don't need to look up all of the capture groups and do
548 // replacements inside the replacement string. We just push it
549 // at each match and be done with it.
550 if let Some(rep
) = rep
.no_expansion() {
551 let mut it
= self.find_iter(text
).enumerate().peekable();
552 if it
.peek().is_none() {
553 return Cow
::Borrowed(text
);
555 let mut new
= String
::with_capacity(text
.len());
556 let mut last_match
= 0;
558 if limit
> 0 && i
>= limit
{
561 new
.push_str(&text
[last_match
..m
.start()]);
563 last_match
= m
.end();
565 new
.push_str(&text
[last_match
..]);
566 return Cow
::Owned(new
);
569 // The slower path, which we use if the replacement needs access to
571 let mut it
= self.captures_iter(text
).enumerate().peekable();
572 if it
.peek().is_none() {
573 return Cow
::Borrowed(text
);
575 let mut new
= String
::with_capacity(text
.len());
576 let mut last_match
= 0;
578 if limit
> 0 && i
>= limit
{
581 // unwrap on 0 is OK because captures only reports matches
582 let m
= cap
.get(0).unwrap();
583 new
.push_str(&text
[last_match
..m
.start()]);
584 rep
.replace_append(&cap
, &mut new
);
585 last_match
= m
.end();
587 new
.push_str(&text
[last_match
..]);
592 /// Advanced or "lower level" search methods.
594 /// Returns the end location of a match in the text given.
596 /// This method may have the same performance characteristics as
597 /// `is_match`, except it provides an end location for a match. In
598 /// particular, the location returned *may be shorter* than the proper end
599 /// of the leftmost-first match.
603 /// Typically, `a+` would match the entire first sequence of `a` in some
604 /// text, but `shortest_match` can give up as soon as it sees the first
608 /// # extern crate regex; use regex::Regex;
610 /// let text = "aaaaa";
611 /// let pos = Regex::new(r"a+").unwrap().shortest_match(text);
612 /// assert_eq!(pos, Some(1));
615 pub fn shortest_match(&self, text
: &str) -> Option
<usize> {
616 self.shortest_match_at(text
, 0)
619 /// Returns the same as shortest_match, but starts the search at the given
622 /// The significance of the starting point is that it takes the surrounding
623 /// context into consideration. For example, the `\A` anchor can only
624 /// match when `start == 0`.
625 pub fn shortest_match_at(
630 self.0.searcher_str().shortest_match_at(text
, start
)
633 /// Returns the same as is_match, but starts the search at the given
636 /// The significance of the starting point is that it takes the surrounding
637 /// context into consideration. For example, the `\A` anchor can only
638 /// match when `start == 0`.
639 pub fn is_match_at(&self, text
: &str, start
: usize) -> bool
{
640 self.shortest_match_at(text
, start
).is_some()
643 /// Returns the same as find, but starts the search at the given
646 /// The significance of the starting point is that it takes the surrounding
647 /// context into consideration. For example, the `\A` anchor can only
648 /// match when `start == 0`.
653 ) -> Option
<Match
<'t
>> {
656 .find_at(text
, start
)
657 .map(|(s
, e
)| Match
::new(text
, s
, e
))
660 /// This is like `captures`, but uses
661 /// [`CaptureLocations`](struct.CaptureLocations.html)
663 /// [`Captures`](struct.Captures.html) in order to amortize allocations.
665 /// To create a `CaptureLocations` value, use the
666 /// `Regex::capture_locations` method.
668 /// This returns the overall match if this was successful, which is always
669 /// equivalence to the `0`th capture group.
670 pub fn captures_read
<'t
>(
672 locs
: &mut CaptureLocations
,
674 ) -> Option
<Match
<'t
>> {
675 self.captures_read_at(locs
, text
, 0)
678 /// Returns the same as captures, but starts the search at the given
679 /// offset and populates the capture locations given.
681 /// The significance of the starting point is that it takes the surrounding
682 /// context into consideration. For example, the `\A` anchor can only
683 /// match when `start == 0`.
684 pub fn captures_read_at
<'t
>(
686 locs
: &mut CaptureLocations
,
689 ) -> Option
<Match
<'t
>> {
692 .captures_read_at(&mut locs
.0, text
, start
)
693 .map(|(s
, e
)| Match
::new(text
, s
, e
))
696 /// An undocumented alias for `captures_read_at`.
698 /// The `regex-capi` crate previously used this routine, so to avoid
699 /// breaking that crate, we continue to provide the name as an undocumented
702 pub fn read_captures_at
<'t
>(
704 locs
: &mut CaptureLocations
,
707 ) -> Option
<Match
<'t
>> {
708 self.captures_read_at(locs
, text
, start
)
712 /// Auxiliary methods.
714 /// Returns the original string of this regex.
715 pub fn as_str(&self) -> &str {
716 &self.0.regex_strings()[0]
719 /// Returns an iterator over the capture names.
720 pub fn capture_names(&self) -> CaptureNames
{
721 CaptureNames(self.0.capture_names().iter())
724 /// Returns the number of captures.
725 pub fn captures_len(&self) -> usize {
726 self.0.capture_names().len()
729 /// Returns an empty set of capture locations that can be reused in
730 /// multiple calls to `captures_read` or `captures_read_at`.
731 pub fn capture_locations(&self) -> CaptureLocations
{
732 CaptureLocations(self.0.searcher_str().locations())
735 /// An alias for `capture_locations` to preserve backward compatibility.
737 /// The `regex-capi` crate uses this method, so to avoid breaking that
738 /// crate, we continue to export it as an undocumented API.
740 pub fn locations(&self) -> CaptureLocations
{
741 CaptureLocations(self.0.searcher_str().locations())
745 /// An iterator over the names of all possible captures.
747 /// `None` indicates an unnamed capture; the first element (capture 0, the
748 /// whole matched region) is always unnamed.
750 /// `'r` is the lifetime of the compiled regular expression.
751 #[derive(Clone, Debug)]
752 pub struct CaptureNames
<'r
>(::std
::slice
::Iter
<'r
, Option
<String
>>);
754 impl<'r
> Iterator
for CaptureNames
<'r
> {
755 type Item
= Option
<&'r
str>;
757 fn next(&mut self) -> Option
<Option
<&'r
str>> {
761 .map(|slot
| slot
.as_ref().map(|name
| name
.as_ref()))
764 fn size_hint(&self) -> (usize, Option
<usize>) {
768 fn count(self) -> usize {
773 impl<'r
> ExactSizeIterator
for CaptureNames
<'r
> {}
775 impl<'r
> FusedIterator
for CaptureNames
<'r
> {}
777 /// Yields all substrings delimited by a regular expression match.
779 /// `'r` is the lifetime of the compiled regular expression and `'t` is the
780 /// lifetime of the string being split.
782 pub struct Split
<'r
, 't
> {
783 finder
: Matches
<'r
, 't
>,
787 impl<'r
, 't
> Iterator
for Split
<'r
, 't
> {
790 fn next(&mut self) -> Option
<&'t
str> {
791 let text
= self.finder
.0.text();
792 match self.finder
.next() {
794 if self.last
> text
.len() {
797 let s
= &text
[self.last
..];
798 self.last
= text
.len() + 1; // Next call will return None
803 let matched
= &text
[self.last
..m
.start()];
811 impl<'r
, 't
> FusedIterator
for Split
<'r
, 't
> {}
813 /// Yields at most `N` substrings delimited by a regular expression match.
815 /// The last substring will be whatever remains after splitting.
817 /// `'r` is the lifetime of the compiled regular expression and `'t` is the
818 /// lifetime of the string being split.
820 pub struct SplitN
<'r
, 't
> {
821 splits
: Split
<'r
, 't
>,
825 impl<'r
, 't
> Iterator
for SplitN
<'r
, 't
> {
828 fn next(&mut self) -> Option
<&'t
str> {
835 return self.splits
.next();
838 let text
= self.splits
.finder
.0.text();
839 if self.splits
.last
> text
.len() {
840 // We've already returned all substrings.
843 // self.n == 0, so future calls will return None immediately
844 Some(&text
[self.splits
.last
..])
848 fn size_hint(&self) -> (usize, Option
<usize>) {
853 impl<'r
, 't
> FusedIterator
for SplitN
<'r
, 't
> {}
855 /// CaptureLocations is a low level representation of the raw offsets of each
858 /// You can think of this as a lower level
859 /// [`Captures`](struct.Captures.html), where this type does not support
860 /// named capturing groups directly and it does not borrow the text that these
861 /// offsets were matched on.
863 /// Primarily, this type is useful when using the lower level `Regex` APIs
864 /// such as `read_captures`, which permits amortizing the allocation in which
865 /// capture match locations are stored.
867 /// In order to build a value of this type, you'll need to call the
868 /// `capture_locations` method on the `Regex` being used to execute the search.
869 /// The value returned can then be reused in subsequent searches.
870 #[derive(Clone, Debug)]
871 pub struct CaptureLocations(re_trait
::Locations
);
873 /// A type alias for `CaptureLocations` for backwards compatibility.
875 /// Previously, we exported `CaptureLocations` as `Locations` in an
876 /// undocumented API. To prevent breaking that code (e.g., in `regex-capi`),
877 /// we continue re-exporting the same undocumented API.
879 pub type Locations
= CaptureLocations
;
881 impl CaptureLocations
{
882 /// Returns the start and end positions of the Nth capture group. Returns
883 /// `None` if `i` is not a valid capture group or if the capture group did
884 /// not match anything. The positions returned are *always* byte indices
885 /// with respect to the original string matched.
887 pub fn get(&self, i
: usize) -> Option
<(usize, usize)> {
891 /// Returns the total number of capturing groups.
893 /// This is always at least `1` since every regex has at least `1`
894 /// capturing group that corresponds to the entire match.
896 pub fn len(&self) -> usize {
900 /// An alias for the `get` method for backwards compatibility.
902 /// Previously, we exported `get` as `pos` in an undocumented API. To
903 /// prevent breaking that code (e.g., in `regex-capi`), we continue
904 /// re-exporting the same undocumented API.
907 pub fn pos(&self, i
: usize) -> Option
<(usize, usize)> {
912 /// Captures represents a group of captured strings for a single match.
914 /// The 0th capture always corresponds to the entire match. Each subsequent
915 /// index corresponds to the next capture group in the regex. If a capture
916 /// group is named, then the matched string is *also* available via the `name`
917 /// method. (Note that the 0th capture is always unnamed and so must be
918 /// accessed with the `get` method.)
920 /// Positions returned from a capture group are always byte indices.
922 /// `'t` is the lifetime of the matched text.
923 pub struct Captures
<'t
> {
925 locs
: re_trait
::Locations
,
926 named_groups
: Arc
<HashMap
<String
, usize>>,
929 impl<'t
> Captures
<'t
> {
930 /// Returns the match associated with the capture group at index `i`. If
931 /// `i` does not correspond to a capture group, or if the capture group
932 /// did not participate in the match, then `None` is returned.
936 /// Get the text of the match with a default of an empty string if this
937 /// group didn't participate in the match:
940 /// # use regex::Regex;
941 /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap();
942 /// let caps = re.captures("abc123").unwrap();
944 /// let text1 = caps.get(1).map_or("", |m| m.as_str());
945 /// let text2 = caps.get(2).map_or("", |m| m.as_str());
946 /// assert_eq!(text1, "123");
947 /// assert_eq!(text2, "");
949 pub fn get(&self, i
: usize) -> Option
<Match
<'t
>> {
950 self.locs
.pos(i
).map(|(s
, e
)| Match
::new(self.text
, s
, e
))
953 /// Returns the match for the capture group named `name`. If `name` isn't a
954 /// valid capture group or didn't match anything, then `None` is returned.
955 pub fn name(&self, name
: &str) -> Option
<Match
<'t
>> {
956 self.named_groups
.get(name
).and_then(|&i
| self.get(i
))
959 /// An iterator that yields all capturing matches in the order in which
960 /// they appear in the regex. If a particular capture group didn't
961 /// participate in the match, then `None` is yielded for that capture.
963 /// The first match always corresponds to the overall match of the regex.
964 pub fn iter
<'c
>(&'c
self) -> SubCaptureMatches
<'c
, 't
> {
965 SubCaptureMatches { caps: self, it: self.locs.iter() }
968 /// Expands all instances of `$name` in `replacement` to the corresponding
969 /// capture group `name`, and writes them to the `dst` buffer given.
971 /// `name` may be an integer corresponding to the index of the capture
972 /// group (counted by order of opening parenthesis where `0` is the
973 /// entire match) or it can be a name (consisting of letters, digits or
974 /// underscores) corresponding to a named capture group.
976 /// If `name` isn't a valid capture group (whether the name doesn't exist
977 /// or isn't a valid index), then it is replaced with the empty string.
979 /// The longest possible name consisting of the characters `[_0-9A-Za-z]`
980 /// is used. e.g., `$1a` looks up the capture group named `1a` and not the
981 /// capture group at index `1`. To exert more precise control over the
982 /// name, or to refer to a capture group name that uses characters outside
983 /// of `[_0-9A-Za-z]`, use braces, e.g., `${1}a` or `${foo[bar].baz}`. When
984 /// using braces, any sequence of characters is permitted. If the sequence
985 /// does not refer to a capture group name in the corresponding regex, then
986 /// it is replaced with an empty string.
988 /// To write a literal `$` use `$$`.
989 pub fn expand(&self, replacement
: &str, dst
: &mut String
) {
990 expand_str(self, replacement
, dst
)
993 /// Returns the number of captured groups.
995 /// This is always at least `1`, since every regex has at least one capture
996 /// group that corresponds to the full match.
998 pub fn len(&self) -> usize {
1003 impl<'t
> fmt
::Debug
for Captures
<'t
> {
1004 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1005 f
.debug_tuple("Captures").field(&CapturesDebug(self)).finish()
1009 struct CapturesDebug
<'c
, 't
: 'c
>(&'c Captures
<'t
>);
1011 impl<'c
, 't
> fmt
::Debug
for CapturesDebug
<'c
, 't
> {
1012 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1013 // We'd like to show something nice here, even if it means an
1014 // allocation to build a reverse index.
1015 let slot_to_name
: HashMap
<&usize, &String
> =
1016 self.0.named_groups
.iter().map(|(a
, b
)| (b
, a
)).collect();
1017 let mut map
= f
.debug_map();
1018 for (slot
, m
) in self.0.locs
.iter().enumerate() {
1019 let m
= m
.map(|(s
, e
)| &self.0.text
[s
..e
]);
1020 if let Some(name
) = slot_to_name
.get(&slot
) {
1021 map
.entry(&name
, &m
);
1023 map
.entry(&slot
, &m
);
1030 /// Get a group by index.
1032 /// `'t` is the lifetime of the matched text.
1034 /// The text can't outlive the `Captures` object if this method is
1035 /// used, because of how `Index` is defined (normally `a[i]` is part
1036 /// of `a` and can't outlive it); to do that, use `get()` instead.
1040 /// If there is no group at the given index.
1041 impl<'t
> Index
<usize> for Captures
<'t
> {
1044 fn index(&self, i
: usize) -> &str {
1046 .map(|m
| m
.as_str())
1047 .unwrap_or_else(|| panic
!("no group at index '{}'", i
))
1051 /// Get a group by name.
1053 /// `'t` is the lifetime of the matched text and `'i` is the lifetime
1054 /// of the group name (the index).
1056 /// The text can't outlive the `Captures` object if this method is
1057 /// used, because of how `Index` is defined (normally `a[i]` is part
1058 /// of `a` and can't outlive it); to do that, use `name` instead.
1062 /// If there is no group named by the given value.
1063 impl<'t
, 'i
> Index
<&'i
str> for Captures
<'t
> {
1066 fn index
<'a
>(&'a
self, name
: &'i
str) -> &'a
str {
1068 .map(|m
| m
.as_str())
1069 .unwrap_or_else(|| panic
!("no group named '{}'", name
))
1073 /// An iterator that yields all capturing matches in the order in which they
1074 /// appear in the regex.
1076 /// If a particular capture group didn't participate in the match, then `None`
1077 /// is yielded for that capture. The first match always corresponds to the
1078 /// overall match of the regex.
1080 /// The lifetime `'c` corresponds to the lifetime of the `Captures` value, and
1081 /// the lifetime `'t` corresponds to the originally matched text.
1082 #[derive(Clone, Debug)]
1083 pub struct SubCaptureMatches
<'c
, 't
: 'c
> {
1084 caps
: &'c Captures
<'t
>,
1085 it
: SubCapturesPosIter
<'c
>,
1088 impl<'c
, 't
> Iterator
for SubCaptureMatches
<'c
, 't
> {
1089 type Item
= Option
<Match
<'t
>>;
1091 fn next(&mut self) -> Option
<Option
<Match
<'t
>>> {
1094 .map(|cap
| cap
.map(|(s
, e
)| Match
::new(self.caps
.text
, s
, e
)))
1098 impl<'c
, 't
> FusedIterator
for SubCaptureMatches
<'c
, 't
> {}
1100 /// An iterator that yields all non-overlapping capture groups matching a
1101 /// particular regular expression.
1103 /// The iterator stops when no more matches can be found.
1105 /// `'r` is the lifetime of the compiled regular expression and `'t` is the
1106 /// lifetime of the matched string.
1108 pub struct CaptureMatches
<'r
, 't
>(
1109 re_trait
::CaptureMatches
<'t
, ExecNoSyncStr
<'r
>>,
1112 impl<'r
, 't
> Iterator
for CaptureMatches
<'r
, 't
> {
1113 type Item
= Captures
<'t
>;
1115 fn next(&mut self) -> Option
<Captures
<'t
>> {
1116 self.0.next().map(|locs
| Captures
{
1117 text
: self.0.text(),
1119 named_groups
: self.0.regex().capture_name_idx().clone(),
1124 impl<'r
, 't
> FusedIterator
for CaptureMatches
<'r
, 't
> {}
1126 /// An iterator over all non-overlapping matches for a particular string.
1128 /// The iterator yields a `Match` value. The iterator stops when no more
1129 /// matches can be found.
1131 /// `'r` is the lifetime of the compiled regular expression and `'t` is the
1132 /// lifetime of the matched string.
1134 pub struct Matches
<'r
, 't
>(re_trait
::Matches
<'t
, ExecNoSyncStr
<'r
>>);
1136 impl<'r
, 't
> Iterator
for Matches
<'r
, 't
> {
1137 type Item
= Match
<'t
>;
1139 fn next(&mut self) -> Option
<Match
<'t
>> {
1140 let text
= self.0.text();
1141 self.0.next().map(|(s
, e
)| Match
::new(text
, s
, e
))
1145 impl<'r
, 't
> FusedIterator
for Matches
<'r
, 't
> {}
1147 /// Replacer describes types that can be used to replace matches in a string.
1149 /// In general, users of this crate shouldn't need to implement this trait,
1150 /// since implementations are already provided for `&str` along with other
1151 /// variants of string types and `FnMut(&Captures) -> String` (or any
1152 /// `FnMut(&Captures) -> T` where `T: AsRef<str>`), which covers most use cases.
1153 pub trait Replacer
{
1154 /// Appends text to `dst` to replace the current match.
1156 /// The current match is represented by `caps`, which is guaranteed to
1157 /// have a match at capture group `0`.
1159 /// For example, a no-op replacement would be
1160 /// `dst.push_str(caps.get(0).unwrap().as_str())`.
1161 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
);
1163 /// Return a fixed unchanging replacement string.
1165 /// When doing replacements, if access to `Captures` is not needed (e.g.,
1166 /// the replacement byte string does not need `$` expansion), then it can
1167 /// be beneficial to avoid finding sub-captures.
1169 /// In general, this is called once for every call to `replacen`.
1170 fn no_expansion
<'r
>(&'r
mut self) -> Option
<Cow
<'r
, str>> {
1174 /// Return a `Replacer` that borrows and wraps this `Replacer`.
1176 /// This is useful when you want to take a generic `Replacer` (which might
1177 /// not be cloneable) and use it without consuming it, so it can be used
1183 /// use regex::{Regex, Replacer};
1185 /// fn replace_all_twice<R: Replacer>(
1190 /// let dst = re.replace_all(src, rep.by_ref());
1191 /// let dst = re.replace_all(&dst, rep.by_ref());
1192 /// dst.into_owned()
1195 fn by_ref
<'r
>(&'r
mut self) -> ReplacerRef
<'r
, Self> {
1200 /// By-reference adaptor for a `Replacer`
1202 /// Returned by [`Replacer::by_ref`](trait.Replacer.html#method.by_ref).
1204 pub struct ReplacerRef
<'a
, R
: ?Sized
+ 'a
>(&'a
mut R
);
1206 impl<'a
, R
: Replacer
+ ?Sized
+ 'a
> Replacer
for ReplacerRef
<'a
, R
> {
1207 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
) {
1208 self.0.replace_append(caps
, dst
)
1210 fn no_expansion(&mut self) -> Option
<Cow
<str>> {
1211 self.0.no_expansion()
1215 impl<'a
> Replacer
for &'a
str {
1216 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
) {
1217 caps
.expand(*self, dst
);
1220 fn no_expansion(&mut self) -> Option
<Cow
<str>> {
1225 impl<'a
> Replacer
for &'a String
{
1226 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
) {
1227 self.as_str().replace_append(caps
, dst
)
1230 fn no_expansion(&mut self) -> Option
<Cow
<str>> {
1235 impl Replacer
for String
{
1236 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
) {
1237 self.as_str().replace_append(caps
, dst
)
1240 fn no_expansion(&mut self) -> Option
<Cow
<str>> {
1245 impl<'a
> Replacer
for Cow
<'a
, str> {
1246 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
) {
1247 self.as_ref().replace_append(caps
, dst
)
1250 fn no_expansion(&mut self) -> Option
<Cow
<str>> {
1255 impl<'a
> Replacer
for &'a Cow
<'a
, str> {
1256 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
) {
1257 self.as_ref().replace_append(caps
, dst
)
1260 fn no_expansion(&mut self) -> Option
<Cow
<str>> {
1265 fn no_expansion
<T
: AsRef
<str>>(t
: &T
) -> Option
<Cow
<str>> {
1267 match find_byte(b'$'
, s
.as_bytes()) {
1269 None
=> Some(Cow
::Borrowed(s
)),
1273 impl<F
, T
> Replacer
for F
1275 F
: FnMut(&Captures
) -> T
,
1278 fn replace_append(&mut self, caps
: &Captures
, dst
: &mut String
) {
1279 dst
.push_str((*self)(caps
).as_ref());
1283 /// `NoExpand` indicates literal string replacement.
1285 /// It can be used with `replace` and `replace_all` to do a literal string
1286 /// replacement without expanding `$name` to their corresponding capture
1287 /// groups. This can be both convenient (to avoid escaping `$`, for example)
1288 /// and performant (since capture groups don't need to be found).
1290 /// `'t` is the lifetime of the literal text.
1291 #[derive(Clone, Debug)]
1292 pub struct NoExpand
<'t
>(pub &'t
str);
1294 impl<'t
> Replacer
for NoExpand
<'t
> {
1295 fn replace_append(&mut self, _
: &Captures
, dst
: &mut String
) {
1296 dst
.push_str(self.0);
1299 fn no_expansion(&mut self) -> Option
<Cow
<str>> {
1300 Some(Cow
::Borrowed(self.0))