fuzzy

package
v0.7.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 21, 2026 License: MIT Imports: 3 Imported by: 2

README

Fuzzy String Matching Package

A high-performance fuzzy string matching library for Go, optimized for CLI command suggestions and similar use cases.

Features

  • Multi-tier matching algorithm: Exact → Substring → Word boundary → Levenshtein distance
  • High performance: 3-8x faster than naive implementations
  • Memory efficient: Zero allocations for distance calculations via buffer pooling
  • Flexible API: Search for multiple matches or find the best match
  • Type-safe: Generic interface for matching any named items
  • Well-tested: Comprehensive test suite with 37 test cases

Installation

go get github.com/paularlott/cli/fuzzy

Quick Start

package main

import (
    "fmt"
    "github.com/paularlott/cli/fuzzy"
)

func main() {
    // Create items to search
    items := []fuzzy.NamedItem{
        fuzzy.NamedItemString{ID: 1, Name: "server"},
        fuzzy.NamedItemString{ID: 2, Name: "start"},
        fuzzy.NamedItemString{ID: 3, Name: "stop"},
        fuzzy.NamedItemString{ID: 4, Name: "status"},
    }

    // Search for matches
    results := fuzzy.Search("srvr", items, fuzzy.DefaultOptions())

    for _, r := range results {
        fmt.Printf("%s (score: %.2f)\n", r.Name, r.Score)
    }
    // Output: server (score: 0.80)
}

API

Search Function

Find multiple matches sorted by relevance:

results := fuzzy.Search(query string, items []NamedItem, opts Options) []Result
Best Function

Find the single best match:

result := fuzzy.Best(query string, items []NamedItem, entityType string, opts Options) BestResult
Score Function

Calculate similarity between two strings:

score := fuzzy.Score(s1, s2 string) float64  // Returns 0.0 to 1.0
Options
type Options struct {
    MaxResults int     // Maximum results to return (default: 5)
    Threshold  float64 // Minimum score threshold (default: 0.5)
}

Custom Items

Implement the NamedItem interface for your types:

type Command struct {
    ID   int
    Name string
}

func (c Command) GetID() int    { return c.ID }
func (c Command) GetName() string { return c.Name }

// Now use with fuzzy.Search
commands := []fuzzy.NamedItem{
    Command{ID: 1, Name: "deploy"},
    Command{ID: 2, Name: "build"},
}

Algorithm

The fuzzy matcher uses a four-tier approach:

  1. Exact match (score: 1.0) - Case-insensitive exact match
  2. Substring match (score: 0.9) - Query is substring of name
  3. Word boundary match (score: 0.85) - Query matches word prefix
  4. Levenshtein distance (score: 0.0-1.0) - Edit distance based similarity

This ensures fast matches for common cases while falling back to fuzzy matching when needed.

Use Cases

  • CLI command suggestions ("Did you mean...?")
  • Autocomplete and search
  • Typo correction
  • Tool/function name matching
  • Any scenario requiring fuzzy string matching

License

MIT License - See LICENSE.txt for details

Documentation

Overview

Package fuzzy provides fuzzy string matching utilities using a multi-tier matching algorithm (exact → substring → word boundary → Levenshtein distance).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatSuggestions

func FormatSuggestions(suggestions []string) string

FormatSuggestions formats a list of suggestion names into a readable string.

func Score

func Score(s1, s2 string) float64

Score calculates the similarity score between two strings. Returns a value between 0.0 (completely different) and 1.0 (identical).

Types

type BestResult

type BestResult struct {
	Found bool    // True if a match was found
	ID    int     // The matched item's ID (0 if not found)
	Name  string  // The matched item's name (empty if not found)
	Score float64 // Match score (0 if not found)
	Error string  // Error message with suggestions (empty if found)
}

BestResult represents the result of a Best() call.

func Best

func Best(query string, items []NamedItem, entityType string, opts Options) BestResult

Best finds the best match for a query and returns a formatted result. If no match is found, returns a result with Error containing suggestions.

type NamedItem

type NamedItem interface {
	GetID() int
	GetName() string
}

NamedItem represents an item with an ID and Name for fuzzy matching. Items must implement this interface to be searchable.

type NamedItemString

type NamedItemString struct {
	ID   int
	Name string
}

NamedItemString is a simple implementation of NamedItem for string-based items.

func (NamedItemString) GetID

func (n NamedItemString) GetID() int

func (NamedItemString) GetName

func (n NamedItemString) GetName() string

type Options

type Options struct {
	MaxResults int     // Maximum number of results to return (default: 5)
	Threshold  float64 // Minimum score threshold 0.0-1.0 (default: 0.5)
}

Options configures the fuzzy search behavior.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns Options with sensible defaults.

type Result

type Result struct {
	ID    int     // The matched item's ID
	Name  string  // The matched item's name
	Score float64 // Match score (0.0 to 1.0, higher is better)
}

Result represents a single fuzzy match result.

func Search(query string, items []NamedItem, opts Options) []Result

Search performs a fuzzy search and returns multiple matches sorted by score. Returns an empty slice if no matches are found.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL