如何在Java中执行字符串Diffs?

Ser*_*Amo 47 java diff

我需要在Java字符串之间执行Diffs.我希望能够使用原始字符串和diff版本重建字符串.有没有人用Java做过这个?你用什么图书馆?

String a1; // This can be a long text
String a2; // ej. above text with spelling corrections
String a3; // ej. above text with spelling corrections and an additional sentence

Diff diff = new Diff();
String differences_a1_a2 = Diff.getDifferences(a,changed_a);
String differences_a2_a3 = Diff.getDifferences(a,changed_a);    
String[] diffs = new String[]{a,differences_a1_a2,differences_a2_a3};
String new_a3 = Diff.build(diffs);
a3.equals(new_a3); // this is true
Run Code Online (Sandbox Code Playgroud)

ber*_*rdn 48

这个库似乎可以解决这个问题:google-diff-match-patch.它可以根据差异创建补丁字符串,并允许重新应用补丁.

编辑:另一种解决方案可能是https://code.google.com/p/java-diff-utils/

  • google-diff-match-patch的Maven存储库是[那里](https://bitbucket.org/cowwoc/google-diff-match-patch/wiki/Home). (6认同)
  • 主动维护的java-diff-utils分支似乎是https://github.com/bkromhout/java-diff-utils (5认同)
  • 维护的分叉现在似乎是 https://github.com/java-diff-utils/java-diff-utils (2认同)

Pau*_*lan 22

Apache Commons有String diff

org.apache.commons.lang.StringUtils

StringUtils.difference("foobar", "foo");
Run Code Online (Sandbox Code Playgroud)

  • 它返回第二个String的剩余部分,从它与第一个字符串的不同开始.这对我来说效率不高,因为我会使用大文本.请参阅:StringUtils.difference("ab","abxyz") - >"xyz"StringUtils.difference("ab","xyzab") - >"xyzab"; (5认同)
  • 还要注意这个问题:`StringUtils.difference("abc", "") = ""` `StringUtils.difference("abc", "abc") = ""` (2认同)