227. trim_matches — Strip the Same Char Off Both Ends, However Many There Are
trim() only knows about whitespace, and strip_prefix peels off one occurrence. When you need to shave every leading and trailing . (or 0, or quote) off a string, reach for trim_matches.
The hand-rolled trim
You’ve got a string padded with some character and want it gone from both ends — but only the ends:
| |
Looping strip_prefix/strip_suffix until they stop matching works, but it’s a chore. trim_matches does exactly that for you — it removes all consecutive matches from both ends and leaves the middle alone:
| |
One end at a time
There are directional versions when you only care about one side:
| |
The pattern can be a closure or a set of chars
The argument is a Pattern, so you’re not limited to a single char. Pass a closure to trim by predicate, or an array of chars to trim any of them:
| |
Note trim_end_matches("--") strips the whole substring repeatedly, not a set of chars — that’s the difference between passing "--" and passing ['-'].