A C# library for applying text diffs and replacements with built-in fuzzy matching. Supports OpenAI's V4A patch format and Anthropic-style str_replace operations.
dotnet add package PatchSharp
Targets netstandard2.1, net8.0, and net10.0.
All methods are on the static class PatchSharp.ApplyPatch.
usingPatchSharp;varoriginal="line one\nline two\nline three\n";vardiff=@"*** original.txt line one-line two+line 2 line three";varresult=ApplyPatch.Apply(original,diff);// "line one\nline 2\nline three\n"vardiff=@"*** new-file.txt+hello+world";varresult=ApplyPatch.Create(diff);// "hello\nworld\n"varinput="function hello() {\n return 'world';\n}\n";varresult=ApplyPatch.StrReplace(input,oldStr:" return 'world';",newStr:" return 'hello world';");Replace all occurrences:
varresult=ApplyPatch.StrReplace(input,"old","new",allowMulti:true);Use a regex pattern:
varresult=ApplyPatch.StrReplace(input,@"v\d+\.\d+","v2.0",useRegex:true);All methods throw PatchApplyException on failure:
try{ApplyPatch.Apply(input,diff);}catch(PatchApplyExceptionex){Console.WriteLine(ex.Message);Console.WriteLine(ex.LineNumber);// line in the diff where the error occurredConsole.WriteLine(ex.Fuzz);// fuzzy match level used (0 = exact)Console.WriteLine(ex.Context);// surrounding context for diagnostics}When an exact match isn't found, PatchSharp tries progressively looser matching:
| Fuzz level | Strategy |
|---|---|
| 0 | Exact match |
| 1 | Ignore trailing whitespace |
| 100 | Ignore leading and trailing whitespace |
| 500 | Skip blank lines (handles AI models omitting blank lines from diff context) |
| 1000 | Unicode normalization (smart quotes → ASCII quotes, em-dashes → hyphens, etc.) |
The lowest fuzz level that produces a match wins.
*** path/to/file.txt ← file header
@@ context line ← anchor (jump to this line)
unchanged line ← context (space prefix)
-removed line ← deletion
+added line ← insertion
*** End of File ← anchor to end of file
Wrapped in optional *** Begin Patch / *** End Patch markers.
PatchSharp was extracted from Instruct UI, an AI-powered platform that generates production-ready Blazor UI code from text descriptions and screenshots. These patching and replacement algorithms are battle-tested across thousands of AI-generated code edits in Instruct UI's multi-agent workflow, where reliable diff application is critical for compiling and rendering live previews.
MIT