AlgoTales · Roadmap

Pattern matching

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Pattern matching means finding where a short piece of text, the pattern, appears inside a longer text. The simple method slides the pattern along one position at a time and compares letters. It powers search boxes, log tools, scanners and everything that uses strpos or indexOf.

Practical use cases

  • Web app: Finding a customer name in a log file. Support staff paste a customer name into a log viewer to see every line that mentions it. The viewer slides the name along each line, comparing letters, and highlights every match. A day of logs with a million lines can be scanned in a moment.
  • Web app: Site search and highlighting. A blog search box finds posts containing the typed phrase and bolds the match in the preview. PHP strpos or JavaScript indexOf is doing the sliding and comparing for you, and knowing that explains why searching huge text on every keystroke needs care, such as waiting until the user pauses typing, or building an index.
  • System: Virus scanners and DNA search. Antivirus programs look for known byte patterns inside files, and biologists look for short gene patterns inside a genome of billions of letters. Both rely on fast pattern matching methods that avoid redoing comparisons. They remember what has already matched, so letters are not re-read.

The story: Finding the Name on the Wedding List

The wedding list was pinned on the wall: a long line of names with no spaces, ABCABCABD in Mira's simplified notes. Uncle asked her to find where the guest ABD appears. Mira had no computer, only a strip of paper with ABD written on it.

She laid the strip under the first three letters: A-B-C. The third letter did not match D. She slid the strip one step right: B did not match A. One more step, again no. When she reached the seventh position, A-B-D lined up perfectly. "Found it, at position 6!" (counting from 0).

This slide-and-compare method is the simplest form of pattern matching (also called substring search). It is honest, easy to write, and what strpos or indexOf conceptually do. The catch: on texts like AAAAAAAB with a pattern like AAAB it keeps almost matching and wasting effort. Smarter variants (hashing, KMP, Z) fix that, and you are about to meet them.

How to spot this problem, and where you need it

You must find one piece of text inside a much longer one, and the search is getting slow as the text grows or the pattern has many near-matches.

Signs you need it

  • The task says find all occurrences, does the text contain, first position of, or count how many times a word appears.
  • Search over big text, such as logs or documents, is slow, especially with patterns like aaaab inside long runs of a.
  • You call strpos, indexOf or a regular expression inside loops across thousands of documents.

Where to use it in a project

  • Log viewers, admin search boxes and support tools that search large text for names, ids or error messages.
  • Security and moderation features scanning uploads and comments for known patterns or banned words.

The solution

Line the pattern up with the start of the text and compare letter by letter. If all letters match, record the position. If one differs, slide the pattern one place right and try again. This is fine for ordinary searches. For long texts with repetitive patterns, use a smarter method such as KMP or Rabin-Karp, which remember what was already matched. For repeated searches, build an index first.

Payoff: Before: repeated comparisons on nasty text taking seconds. After: a smarter matcher or index returns hits in milliseconds.

Explain it like I am 8

Hold a small sticker with a word on it against a long page. Look at the first letters: same? Then check the next, and next. If any letter is different, slide the sticker one letter to the right and try again. When every letter matches, you found it.

How it works, step by step

  1. Line up the pattern with the start of the text (shift 0).
  2. Compare letter by letter from the pattern's first letter.
  3. On any mismatch, stop this attempt and slide the pattern one step right.
  4. If every letter matches, report the shift: that is where the pattern lives.
  5. Stop sliding when the pattern would hang off the end of the text.

The code in four languages

PHP

<?php
// Naive pattern matching: slide the pattern along the text.
function findAll(string $text, string $pattern): array {
    $n = strlen($text);
    $m = strlen($pattern);
    $found = [];
    for ($shift = 0; $shift + $m <= $n; $shift++) {       // every possible start
        $j = 0;
        while ($j < $m && $text[$shift + $j] === $pattern[$j]) {
            $j++;                                         // letter matched, go on
        }
        if ($j === $m) {
            $found[] = $shift;                            // whole pattern matched
        }
    }
    return $found;
}

echo json_encode(findAll("ABCABCABD", "ABD")) . "\n";    // [6]
echo json_encode(findAll("AAAAA", "AA")) . "\n";          // [0,1,2,3]

JavaScript

// Naive pattern matching: slide the pattern along the text.
function findAll(text, pattern) {
  const n = text.length;
  const m = pattern.length;
  const found = [];
  for (let shift = 0; shift + m <= n; shift++) {          // every possible start
    let j = 0;
    while (j < m && text[shift + j] === pattern[j]) {
      j++;                                                // letter matched, go on
    }
    if (j === m) {
      found.push(shift);                                  // whole pattern matched
    }
  }
  return found;
}

console.log(JSON.stringify(findAll('ABCABCABD', 'ABD')));   // [6]
console.log(JSON.stringify(findAll('AAAAA', 'AA')));         // [0,1,2,3]

Java

import java.util.*;

public class Main {
    // Naive pattern matching: slide the pattern along the text.
    static List<Integer> findAll(String text, String pattern) {
        int n = text.length();
        int m = pattern.length();
        List<Integer> found = new ArrayList<>();
        for (int shift = 0; shift + m <= n; shift++) {        // every possible start
            int j = 0;
            while (j < m && text.charAt(shift + j) == pattern.charAt(j)) {
                j++;                                          // letter matched, go on
            }
            if (j == m) {
                found.add(shift);                             // whole pattern matched
            }
        }
        return found;
    }

    public static void main(String[] args) {
        System.out.println(findAll("ABCABCABD", "ABD"));   // [6]
        System.out.println(findAll("AAAAA", "AA"));        // [0, 1, 2, 3]
    }
}

Go

package main

import "fmt"

// findAll slides the pattern along the text (naive pattern matching).
func findAll(text, pattern string) []int {
	n, m := len(text), len(pattern)
	var found []int
	for shift := 0; shift+m <= n; shift++ { // every possible start
		j := 0
		for j < m && text[shift+j] == pattern[j] {
			j++ // letter matched, go on
		}
		if j == m {
			found = append(found, shift) // whole pattern matched
		}
	}
	return found
}

func main() {
	fmt.Println(findAll("ABCABCABD", "ABD")) // [6]
	fmt.Println(findAll("AAAAA", "AA"))      // [0 1 2 3]
}

Time: O(n × m) worst case · Extra space: O(1). For a text of n letters and a pattern of m letters, each of the n starting spots may compare up to m letters. Usually much faster, but nasty repetitive texts hurt.

Watch out for

  • Looping the shift all the way to n, so the pattern hangs off the end. Stop when shift + m passes n.
  • Returning after the first match when the question asks for all matches (or the reverse).

Quick check

  1. On a mismatch, the naive method…
    • Throws the text away
    • Slides the pattern one step right and restarts
    • Sorts the pattern
  2. In which case does naive matching get slow?
    • Repetitive text like AAAAAAAB with pattern AAAB
    • Short texts
    • Texts with spaces
  3. Text length 10, pattern length 3. How many shifts are tried?
    • 10
    • 7
    • 8