218. str::match_indices — Find Every Match and Its Position in One Pass
Hand-rolling a find loop to locate every occurrence of a substring means juggling a running offset and remembering to skip past each match. match_indices hands you each hit and its byte position as an iterator — no bookkeeping.
The classic way to collect every position of a needle is a loop over find, slicing the remainder each time and adding the offset back by hand:
| |
It works, but the offset arithmetic is exactly the kind of thing you fumble at 5pm. match_indices walks the string for you and yields (byte_index, matched_str) pairs:
| |
It’s lazy and composes like any other iterator, so you can map down to just the indices, or count without allocating at all:
| |
The pattern argument is the full Pattern family — a &str, a char, a closure, or a slice of chars — so you can find runs of a class of characters without a regex:
| |
Matches are non-overlapping and scanned left to right; when you need the last hit first, rmatch_indices walks right to left:
| |
The byte indices are real &str offsets, so they slot straight into slicing and replacement logic without any conversion. When you only care about whether something matches, reach for contains; when you want each location, match_indices already did the bookkeeping.