Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce String::remove_matches to remove all matches of a pattern in a string. #50015

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/liballoc/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1195,6 +1195,54 @@ impl String {
ch
}

/// Remove all matches of pattern `pat` in the `String`.
///
/// # Examples
///
/// ```rust
/// let mut s = String::from("Trees are not green, the sky is not blue.");
/// s.remove_matches("not ");
/// assert_eq!("Trees are green, the sky is blue.", s);
/// ```
///
/// Matches will be detected and removed iteratively, so in cases where
/// patterns overlap, only the first pattern will be removed:
///
/// ```rust
/// let mut s = String::from("banana");
/// s.remove_matches("ana");
/// assert_eq!("bna", s);
/// ```
#[unstable(feature = "string_remove_matches", reason = "new API", issue = "0")]
pub fn remove_matches<'a, P>(&'a mut self, pat: P)
where
P: Pattern<'a>,
{
use core::str::pattern::Searcher;
use core::str::pattern::SearchStep;

loop {
// FIXME: lol
let s = self.clone();
// FIXME: this is inefficient because we'll search from the beginning of the string in
// . each iteration of the loop
let mut searcher = pat.into_searcher(&s);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note that this doesn't compile, because into_searcher immutably borrows the string, and i can't call self.vec.set_len below if it's borrowed. not sure how to proceed

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also into_searcher consumes itself, so there's no way to call it again on a new string slice

match searcher.next() {
SearchStep::Match(start_idx, end_idx) => {
unsafe {
ptr::copy(self.vec.as_ptr().offset(end_idx as isize),
self.vec.as_mut_ptr().offset(start_idx as isize),
end_idx - start_idx);
let new_len = self.vec.len() - (end_idx - start_idx);
self.vec.set_len(new_len);
}
}
SearchStep::Reject(..) => (),
SearchStep::Done => break,
}
}
}

/// Retains only the characters specified by the predicate.
///
/// In other words, remove all characters `c` such that `f(c)` returns `false`.
Expand Down