str::rmatch_indices¶
Level: reference · for working programmers
One line: match_indices from the right — offsets still counted from the front, items yielded back to front.
pub fn rmatch_indices<P: Pattern>(&self, pat: P) -> RMatchIndices<'_, P>
where
for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
Stable since 1.5.0.
The pairing is the same (usize, &str), and the usize still measures from the start of the string. Only the iteration order changes.
That combination is what makes it useful for edits: replacing matches from the end means every offset you have not used yet is still valid, because nothing before it has moved. Working forwards, each edit invalidates the offsets after it.
Example¶
str_rmatch_indices.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let s = "one,two,three";
println!("{:?}", s.match_indices(',').collect::<Vec<(usize, &str)>>());
println!("{:?}", s.rmatch_indices(',').collect::<Vec<(usize, &str)>>());
// Editing from the back keeps the unused offsets valid.
let mut owned = String::from(s);
for (i, m) in s.rmatch_indices(',') {
owned.replace_range(i..i + m.len(), " | ");
}
println!("{owned}");
// The last comma, without collecting everything.
println!("{:?}", s.rmatch_indices(',').next());
}
Verified output of str_rmatch_indices.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
str::match_indices— the forward directionstr::rmatches— the same matches without offsetsstr::rfind— just the last offsetString::replace_range— the in-place edit this pairs with
str::rmatch_indices in the standard library ↗
Po polsku¶
Odwrócona jest tu wyłącznie kolejność zwracania, a nie sposób numerowania: pary to nadal (usize, &str) z przesunięciem liczonym od początku łańcucha, co widać w wydruku — [(3, ","), (7, ",")] do przodu i [(7, ","), (3, ",")] do tyłu. Z tego zestawienia wynika jedyna praktyczna reguła tej strony: edytuj od końca, bo wtedy żadna zmiana nie unieważnia przesunięć, których jeszcze nie użyłeś — w przykładzie "," zamienia się na dłuższe " | ", więc przy pracy od przodu drugie przesunięcie byłoby już nieaktualne. Przydaje się też skrót rmatch_indices(...).next(): to najtańszy sposób na samo ostatnie dopasowanie, bez zbierania reszty do wektora.
Szukaj po polsku: edycja tekstu od końca · przesunięcia bajtowe dopasowań · rust rmatch_indices replace_range · rust match_indices offsets