Algorithmspattern matching index
Pattern Matching: First Index and All Occurrences
TT
Testlaa Team
May 14, 2026•1 min read
Where does the pattern start? Built-ins like str.find return the first index or -1; index raises. For every occurrence, loop with a start offset or use re.finditer when regex is allowed.
Why this shows up in the real world
Search-in-document UIs highlight the first match then jump next. Log parsers locate the first timestamp token in each line.
Core idea (explained for students)
Pattern: i = 0; while True: j = text.find(pat, i); ...; i = j + 1 or start = 0 and while (j := text.find(pat, start)) != -1.
Try this in Python
def all_indices(text: str, pat: str) -> list[int]:
out, start = [], 0
while True:
j = text.find(pat, start)
if j == -1:
return out
out.append(j)
start = j + 1
print(all_indices("abababa", "aba"))
Common mistakes
- Overlapping matches:
findwithstart = j+1skips overlaps; adjust toj+len(pat)-1only if overlaps matter. - Empty pattern: many APIs return
0repeatedly—special-case.
Key takeaways
- Prefer
findoverindexwhen missing is normal. - For many queries on one text, consider preprocessing (suffix array, Z-array) only when profiling demands it.
Tags:
StringsPythonStudents
