Skip to content

Repository files navigation

ktsu.FuzzySearch

A lightweight .NET library that provides fuzzy string matching capabilities, allowing for approximate string matching with intelligent scoring.

LicenseNuGet VersionNuGet VersionNuGet DownloadsGitHub commit activityGitHub contributorsGitHub Actions Workflow Status

Introduction

FuzzySearch is a .NET library that provides fuzzy string matching capabilities with intelligent scoring. It's perfect for implementing search-as-you-type features, command palettes, or any application requiring flexible string matching. This library offers both basic contains-style matching and more sophisticated algorithms that can rank multiple potential matches by relevance.

Features

  • Fuzzy String Matching: Match strings even when they contain typos or missing characters
  • Intelligent Scoring: Rank matches by quality with a smart scoring algorithm
  • Case Insensitivity: Optional case-insensitive matching
  • Filtering Collections: Filter lists of strings and rank results
  • Customizable Parameters: Adjust matching behavior to suit different needs
  • Lightweight: Minimal dependencies, focused on performance
  • Well-tested: Comprehensive test suite ensuring reliability

Installation

Package Manager Console

Install-Package ktsu.FuzzySearch

.NET CLI

dotnet add package ktsu.FuzzySearch

Package Reference

<PackageReferenceInclude="ktsu.FuzzySearch"Version="x.y.z" />

Usage Examples

Basic Matching

The simplest way to check if a string contains characters from a pattern in sequence:

usingktsu.FuzzySearch;classProgram{staticvoidMain(){stringtext="Hello World";stringpattern="hlo";boolisMatch=Fuzzy.Contains(text,pattern);// Returns true}}

Matching with Scoring

To get both a match result and a score that indicates the quality of the match:

usingktsu.FuzzySearch;classProgram{staticvoidMain(){stringtext="Hello World";stringpattern="hlo";varresult=Fuzzy.Match(text,pattern);Console.WriteLine($"Is match: {result.IsMatch}");// TrueConsole.WriteLine($"Score: {result.Score}");// A value between 0-1Console.WriteLine($"Character indices: {result.Indices}");// Indices of matched characters}}

Filtering a Collection

Filter a list of strings and sort them by match quality:

usingktsu.FuzzySearch;classProgram{staticvoidMain(){varitems=newList<string>{"AppDataStorage","Application Settings","Data Store","File System","Storage Provider"};stringpattern="appstor";// Filter and rank by match qualityvarresults=Fuzzy.Filter(items,pattern);foreach(varresultinresults){Console.WriteLine($"{result.Item} (Score: {result.Score})");}// Output might be:// AppDataStorage (Score: 0.89)// Application Settings (Score: 0.65)// Storage Provider (Score: 0.52)}}

Advanced Options

Customize the matching behavior with options:

usingktsu.FuzzySearch;classProgram{staticvoidMain(){varoptions=newFuzzyOptions{CaseSensitive=true,// Default is falseScoreThreshold=0.4,// Minimum score to consider a matchBonusConsecutiveChars=1.5,// Bonus for consecutive matched charactersBonusStartOfWord=2.0,// Bonus for matches at word boundariesPenaltyUnmatched=0.1,// Penalty for unmatched charactersMaxPatternLength=64// Maximum pattern length to consider};stringtext="FileSystemWatcher";stringpattern="FSW";varresult=Fuzzy.Match(text,pattern,options);Console.WriteLine($"Score with custom options: {result.Score}");}}

Object Collections

Filter and match against object collections by providing a selector function:

usingktsu.FuzzySearch;classProgram{classFileItem{publicstringName{get;set;}publicstringPath{get;set;}publiclongSize{get;set;}}staticvoidMain(){varfiles=newList<FileItem>{newFileItem{Name="Document.pdf",Path="/documents/",Size=1024},newFileItem{Name="Presentation.pptx",Path="/presentations/",Size=2048},newFileItem{Name="Spreadsheet.xlsx",Path="/spreadsheets/",Size=512}};stringpattern="doc";// Filter objects using a selector functionvarresults=Fuzzy.Filter(files,pattern, item =>item.Name);foreach(varresultinresults){Console.WriteLine($"{result.Item.Name} (Score: {result.Score})");}}}

API Reference

Fuzzy Static Class

The main class providing fuzzy matching functionality.

Methods

NameParametersReturn TypeDescription
Containsstring text, string pattern, bool caseSensitive = falseboolChecks if the text contains the pattern in sequence
Matchstring text, string pattern, FuzzyOptions options = nullFuzzyResultMatches text against pattern with scoring
FilterIEnumerable<string> items, string pattern, FuzzyOptions options = nullIEnumerable<FuzzyItem<string>>Filters and ranks a collection of strings
Filter<T>IEnumerable<T> items, string pattern, Func<T, string> selector, FuzzyOptions options = nullIEnumerable<FuzzyItem<T>>Filters and ranks a collection of objects using a selector function

FuzzyResult Class

Represents the result of a fuzzy match operation.

Properties

NameTypeDescription
IsMatchboolIndicates if the pattern matches the text
ScoredoubleA value between 0 and 1 indicating match quality (1 is perfect)
Indicesint[]The indices in the text where pattern characters were matched

FuzzyOptions Class

Configuration options for fuzzy matching.

Properties

NameTypeDefaultDescription
CaseSensitiveboolfalseWhether matching should be case-sensitive
ScoreThresholddouble0.3Minimum score required to consider a match valid
BonusConsecutiveCharsdouble1.0Score bonus for consecutive matched characters
BonusStartOfWorddouble1.5Score bonus for matches at word boundaries
PenaltyUnmatcheddouble0.1Score reduction for unmatched characters

Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Please make sure to update tests as appropriate and adhere to the existing coding style.

License

This project is licensed under the MIT License - see the LICENSE.md file for details.

About

Lightweight .NET fuzzy string matching library with intelligent scoring for search-as-you-type, command palettes, and flexible string matching applications.

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages