【问题标题】:Comparing 2 paragraph changes in Java比较Java中的2个段落变化
【发布时间】:2015-03-04 22:41:12
【问题描述】:

我正在开发一个 Java webapp,用户可以在其中更改文本区域。在这方面,他可以写一个段落,一个句子。所以我目前正在尝试做的是用点分隔符分割整个段落。完成后,我想检查哪些句子发生了变化。 我目前正在使用 for 循环进行操作,这不准确,因为我必须将数组的长度设置为两个字符串数组的 Math.minimum。但它不起作用,我从中修改了零字符串。请让我知道我做错了什么。

代码:

 String oldText = "";
 String newText = "";

  if(!(oldNotes.getNotetext().equals(newNotes.getNotetext()))){
            String[] strings = newNotes.getNotetext().split(".");
            if(strings.length>0){
                String[] oldNotesArray = oldNotes.getNotetext().split(".");
                if(oldNotesArray.length>0){
                    for(int i=0; i<Math.min(strings.length,oldNotesArray.length);i++){
                        if(!(strings[i].contains(oldNotesArray[i]))){
                            oldText += oldNotesArray[i];
                            newText += strings[i];
                        }
                    }
               }
                noteHistory.setNewText(newText);
                noteHistory.setHistoryText(oldText);
            } else {

                noteHistory.setNewText(newNotes.getNotetext());
                noteHistory.setHistoryText(oldNotes.getNotetext());
            }
        }

所以基本上在两个字符串中,我只想保存哪些句子已被更改。就这样。请告诉我。谢谢。我只是为了方便使用点分隔符,如果有任何其他高级正则表达式,我不介意使用它。非常感谢。 :-)

编辑 根据建议,我正在尝试使用 google diff-match-patch 库。这是我能够找到的,但在隔离差异方面仍然没有成功。我必须将它们保存在数据库中,所以我也必须标记它们,但我还没有它们。我的代码:

 diff_match_patch diffMatchPatch = new diff_match_patch();
                LinkedList<diff_match_patch.Diff> deltas = diffMatchPatch.diff_main(oldText,newText);
                for(diff_match_patch.Diff d : deltas){
                    if(d.operation== diff_match_patch.Operation.DELETE)
                        oldText += d.text;
                    else if(d.operation== diff_match_patch.Operation.INSERT)
                        newText += d.text;
                    else
                    {
                        oldText += d.text;
                        newText += d.text;
                    }
                }

                System.out.println(oldText);
                System.out.println(newText);

现在当我打印文本时,我可以看到整个 2 段。我做错了什么?

【问题讨论】:

  • .split(".") split 采用正则表达式,. 在正则表达式中是特殊的。你需要逃避它。

标签: java regex string comparison google-diff-match-patch


【解决方案1】:

使用split("\\.") 获取由String 拆分的字符串的精确数组,而不是使用this link of google 的comapre 还可以查看on this artical

【讨论】:

  • 感谢您的链接。你有什么例子我可以在这种情况下使用它吗?非常感谢。
  • @WeareBorg 我没有任何示例,但您可以轻松地 google 并获得它。如果它对您有所帮助,请将其视为赞成或正确答案!!! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多