str::trim_end_matches¶
Level: reference · for working programmers
One line: Removes the pattern from the back as many times as it occurs — the mirror of trim_start_matches.
pub fn trim_end_matches<P: Pattern>(&self, pat: P) -> &str
where
for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
Stable since 1.30.0.
Repeats, accepts a &str, and returns a plain &str whether or not it removed anything — all exactly as at the front.
The two most common uses are trailing slashes on a URL or path, and trailing separators before a join. Both are cases where "however many there are" is genuinely the requirement.
The edge case is the same shape as leading zeros: trimming '.' from "..." leaves "". And trimming a trailing '0' off a decimal number eats the significant one in "1.0" → "1." → and then "10" → "1", which is why numeric formatting wants strip_suffix or an explicit format spec instead.
Example¶
str_trim_end_matches.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
println!("{:?}", "abbb".trim_end_matches('b'));
println!("{:?}", "http://x/y///".trim_end_matches('/'));
println!("{:?}", "a/b/".trim_end_matches("/"));
// One occurrence, reported.
println!("{:?}", "http://x/y///".strip_suffix('/'));
// Trailing zeros: fine on a decimal, wrong on an integer.
for n in ["1.500", "1.0", "10", "100"] {
println!("{:<7} -> {:?}", format!("{n:?}"), n.trim_end_matches('0'));
}
// Which is why a decimal wants the dot handled too.
let d = "1.500";
println!("{:?}", d.trim_end_matches('0').trim_end_matches('.'));
}
Verified output of str_trim_end_matches.rs — regenerated by tools/run_examples.py, never hand-typed.
"a"
"http://x/y"
"a/b"
Some("http://x/y//")
"1.500" -> "1.5"
"1.0" -> "1."
"10" -> "1"
"100" -> "1"
"1.5"
See also¶
str::trim_start_matches— the same, at the frontstr::strip_suffix— one occurrence, and it tells youstr::trim_matches— both ends at oncestr::trim_end— whitespace instead of a pattern
str::trim_end_matches in the standard library ↗
Po polsku¶
Ta metoda zdejmuje wzorzec tyle razy, ile go zastanie, i nigdy nie mówi, czy w ogóle coś zdjęła — zwraca zwykły &str, a nie Option, więc gdy odpowiedź „nie było czego usuwać” ma znaczenie, właściwym narzędziem jest strip_suffix. Pasuje za to idealnie do ukośników na końcu adresu albo ścieżki ("http://x/y///" → "http://x/y") i do separatorów przed sklejaniem, bo tam „ile by ich nie było” jest dokładnie tym, o co chodzi. Pułapkę widać w wyjściu przykładu i dotyczy ona liczb: trim_end_matches('0') nie odróżnia zera wypełniającego od znaczącego, więc "1.0" schodzi do "1.", a "100" aż do "1" — przy formatowaniu liczb sięgaj po strip_suffix albo od razu po specyfikator formatu, a formatując po polsku pamiętaj, że domykające trim_end_matches('.') trzeba wtedy podmienić na przecinek.
Szukaj po polsku: usuwanie ukośnika na końcu ścieżki · zbędne zera na końcu liczby · rust trim_end_matches · rust trim_end_matches removes too much