DEV Community

Cover image for Get Diff and Patch Html
Antoine
Antoine

Posted on

Get Diff and Patch Html

Photo by Markus Spiske on Diff.Match.Patch based on Google library.

Diff

Diff are made of:

  • text (part of the text related)
  • operation to be applied (delete / insert / equal)

It's easy to get diff:

    string a = "<SPAN TITLE=\"i=0\">a&para;<BR></SPAN><DEL STYLE=\"background:#FFE6E6;\" TITLE=\"i=2\">&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>";
    string b = "<SPAN TITLE=\"i=0\">testa&para;<BR></SPAN><DEL STYLE=\":#FFE6E6;\" TITLE=\"i=2\">&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>";

var diffs = DiffMatchPatchModule.Default.DiffMain(a, b);

Enter fullscreen mode Exit fullscreen mode

Please note that diffs will contains a lot of Equal diff !
Result: Result

Patch

It's simple too to get patch from multiple texts!

    string a = "<SPAN TITLE=\"i=0\">a&para;<BR></SPAN><DEL STYLE=\"background:#FFE6E6;\" TITLE=\"i=2\">&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>";
    string b = "<SPAN TITLE=\"i=0\">testa&para;<BR></SPAN><DEL STYLE=\":#FFE6E6;\" TITLE=\"i=2\">&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>";
    string c = "<SPAN TITLE=\"i=0\">a&para;<BR></SPAN><DEL STYLE=\"background:#FFE6E6;\" TITLE=\"i=2\">mon tittre en Or&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>";

    var firstPatch = DiffMatchPatchModule.Default.PatchMake(a, b);
    var secondPatch = DiffMatchPatchModule.Default.PatchMake(a, c);
    DiffMatchPatchModule.Default.PatchApply(secondPatch, DiffMatchPatchModule.Default.PatchApply(firstPatch, a)[0].ToString());

Enter fullscreen mode Exit fullscreen mode

Ouptut:

<SPAN TITLE="i=0">testa&para;<BR></SPAN><DEL STYLE=":#FFE6E6;" TITLE="i=2">mon tittre en Or&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE="background:#E6FFE6;" TITLE="i=2">c&amp;d</INS>
Enter fullscreen mode Exit fullscreen mode

Please note that DiffMatchPatchModule.Default.PatchApply(firstPatch, a) outputs object[] !

Hope that helps !

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay