【问题标题】:How to find and replace without causing duplication如何在不造成重复的情况下查找和替换
【发布时间】:2016-10-14 06:16:07
【问题描述】:

我有一系列文本报告,其中包含以下字段 "Contractile Front velocity"他们

其中一些有"Contractile Front velocitycms" 代替。还有其他类似的术语,其中添加了 cms 等字符。

每个术语都有一个与之关联的数字结果,我正在尝试将术语和结果放入数据库中。数据库字段将是(对于这个例子)"Contractile Front velocitycms"

所以我想将没有与 cms 关联的任何报告(纯文本)字段转换为 Contractile Front velocitycms

因为我有大量的查找替换问题要解决,所以我创建了一个使用 StringUtils.replaceEach 的方法,这样我就可以使用一个简单的冒号分隔的文本文件作为查找字典来进行查找和替换。

public static String FindNReplace(String n) throws IOException{
    String [] split = null;
    ArrayList<String> orig = new ArrayList<String>();
    String [] orig_arr = null;
    ArrayList<String> newDoc = new ArrayList<String>();
    String [] newDoc_arr = null;

    String dictionary="/Users/sebastianzeki/Documents/workspace/PhysiologyUpperGITotalExtractorv2/src/Overview/FindNReplaceDictionary.txt";
    BufferedReader br = new BufferedReader(new FileReader(dictionary));

    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            split=line.split(":");
            System.out.println(split);
            orig.add(split[1]);
            newDoc.add(split[0]);
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
    } finally {
        br.close();
    }

    orig_arr = new String[orig.size()];
    orig_arr = orig.toArray(orig_arr);
    newDoc_arr = new String[newDoc.size()];
    newDoc_arr = newDoc.toArray(newDoc_arr);
    String replacer = StringUtils.replaceEach(n, orig_arr, newDoc_arr);

    return replacer;
}

字典是这样的

PostPr :Post-Prandial
PostPr :Post-prandial
Nausea :nausea

问题是,如果我只是使用我的字典将Contractile Front velocity 替换为Contractile Front velocitycms,那么偶尔,如果收缩前速度cms 已经存在,我会得到Contractile Front velocitycmscms,而replaceEach 不使用正则表达式。谁能想到一个解决方案来避免我提到重复项

【问题讨论】:

    标签: java string replace


    【解决方案1】:

    您想要的是 Negative Lookahead 排除尾随部分。
    负前瞻写为(?!pattern),因此在您的情况下,您希望Contractile Front velocity(?!cms) 作为匹配的模式。

    您可以在RegexPlanet 上试试这个...
    我用过:
    正则表达式: Contractile Front velocity(?!cms)
    输入 1: This Contractile Front velocitycms 已经有了。
    输入 2: 但是这个收缩前沿速度没有。

    当您点击 Test 按钮时,您会看到 Input 2 将“cms”添加到其中,但 Input 1 没有将其加倍。

    【讨论】:

      猜你喜欢
      • 2014-05-04
      • 2023-02-07
      • 1970-01-01
      • 2014-08-21
      • 2021-11-26
      • 2023-03-13
      • 2011-12-22
      • 1970-01-01
      • 2012-02-25
      相关资源
      最近更新 更多