Algorithmspattern matching index

Pattern Matching: First Index and All Occurrences

TT
Testlaa Team
May 14, 20261 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: find with start = j+1 skips overlaps; adjust to j+len(pat)-1 only if overlaps matter.
  • Empty pattern: many APIs return 0 repeatedly—special-case.

Key takeaways

  • Prefer find over index when missing is normal.
  • For many queries on one text, consider preprocessing (suffix array, Z-array) only when profiling demands it.

Tags:

StringsPythonStudents