Replaces at most `limit` non-overlapping matches in `text` with the replacement provided. If `limit` is 0, then all non-overlapping matches are replaced. See the documentation for `replace` for details on how to access capturing group matches in the replacement string.
(
&self,
text: &'t str,
limit: usize,
mut rep: R,
)
| 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>( |
| 538 | &self, |
| 539 | text: &'t str, |
| 540 | limit: usize, |
| 541 | mut rep: R, |
| 542 | ) -> Cow<'t, str> { |
| 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 |
| 545 | // difference: |
| 546 | // |
| 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); |
| 556 | } |
| 557 | let mut new = String::with_capacity(text.len()); |
| 558 | let mut last_match = 0; |
| 559 | for (i, m) in it { |
| 560 | if limit > 0 && i >= limit { |
| 561 | break |
| 562 | } |
| 563 | new.push_str(&text[last_match..m.start()]); |
| 564 | new.push_str(&rep); |
| 565 | last_match = m.end(); |
| 566 | } |
| 567 | new.push_str(&text[last_match..]); |
| 568 | return Cow::Owned(new); |
| 569 | } |
| 570 | |
| 571 | // The slower path, which we use if the replacement needs access to |
| 572 | // capture groups. |
| 573 | let mut it = self.captures_iter(text).enumerate().peekable(); |
| 574 | if it.peek().is_none() { |
| 575 | return Cow::Borrowed(text); |
| 576 | } |
| 577 | let mut new = String::with_capacity(text.len()); |
| 578 | let mut last_match = 0; |
| 579 | for (i, cap) in it { |
| 580 | if limit > 0 && i >= limit { |
| 581 | break |
| 582 | } |
| 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(); |
| 588 | } |
| 589 | new.push_str(&text[last_match..]); |
| 590 | Cow::Owned(new) |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | /// Advanced or "lower level" search methods. |
no test coverage detected