简体   繁体   English

如何查找和删除不区分大小写匹配的字符串?

[英]How to find and remove strings with case insensitive match?

In Java, I have a file contains lines like:在 Java 中,我有一个包含以下行的文件:

abc
cbd
CFG
...

I want to remove CFG from the file if any of the lines matchs a string, which could be 'cfg', 'Cfg', or other case insensitive variations.如果任何行与字符串匹配,我想从文件中删除 CFG,字符串可能是“cfg”、“Cfg”或其他不区分大小写的变体。

If I read the file into a Set, how can I achieve this?如果我将文件读入 Set,我该如何实现? It seems more feasible to do this by reading the file into a List.通过将文件读入列表来做到这一点似乎更可行。

Something like this?像这样的东西?

try (BufferedReader bf = new BufferedReader(new FileReader(new File("PATH TO FILE")));
     BufferedWriter bw = new bw(new FileWriter(new File("PATH TO NEW FILE")))) {
  bf.lines()
      .filter(line -> !line.equalsIgnoreCase("cfg"))
      .forEach(line -> {
        try {
          bw.write(line);
        } catch (IOException e) {
          e.printStackTrace();
        }
  });
}

The only ugly thing is the need for two trys because of not being allowed to throw exceptions from lambdas.唯一丑陋的事情是需要两次尝试,因为不允许从 lambdas 抛出异常。

The following is a "lambda version" of the required code.以下是所需代码的“lambda 版本”。 Thanks to @Sam for the important point about re-raising any suppressed PrintWriter IOException.感谢@Sam关于重新引发任何被抑制的 PrintWriter IOException 的重要观点。

Path in_file = Paths.get("infile");
Path out_file = Paths.get("outfile");
try (PrintWriter pw = new PrintWriter(out_file.toFile())) {
    Files.lines(in_file)
         .filter(line -> !line.equalsIgnoreCase("cfg"))
         .forEach(pw::println);
    if (pw.checkError()) {
        throw new IOException("Exception(s) occurred in PrintWriter");
    }
}

If you need to modify the file in place, then writing to it while reading from it is somewhat more difficult.如果您需要就地修改文件,那么在读取文件的同时写入文件会有些困难。 You could read it all into memory first.您可以先将其全部读入内存。

Path path = new Path("filename");
List<String> lines = Files.lines(path)
                          .filter(line -> !line.equalsIgnoreCase("cfg"))
                          .collect(Collectors.toList());

try(PrintWriter pw = new PrintWriter(path.toFile())) {
    lines.forEach(pw::println);
    if (pw.checkError()) {
        throw new IOException("Exception(s) occurred in PrintWriter");
    }
}

And finally, just in case, a non-lambda solution for compatibility with Java 7:最后,以防万一,一个与 Java 7 兼容的非 lambda 解决方案:

Path in_file = Paths.get("infile");
Path out_file = Paths.get("outfile");
try (BufferReader reader = Files.newBufferedReader(in_file);
         PrintWriter pw = new PrintWriter(out_file.toFile())) {

    String line;
    while((line = reader.readline()) != null) {
        if (!line.equalsIgnoreCase("cfg")) {
            pw.println(line);
        }
    }
    if (pw.checkError()) {
        throw new IOException("Exception(s) occurred in PrintWriter");
    }
}

You can search for the string in the list and remove that using a position.您可以在列表中搜索字符串并使用位置将其删除。

public List<String> removeItemInListIgnoreCase(List<String> items, String itemToRemove){
        if(CollectionUtils.isEmpty(items)) 
        return new ArrayList<String>();
        for(int i=0; i<items.size();i++) {
            if(items.get(i).equalsIgnoreCase(itemToRemove)) {
                items.remove(i);
            }
        }
        return items;
    }

I think TreeSet is what you are looking for, take a look in this link: 我认为TreeSet是您要寻找的东西,请查看以下链接:

Java Set<String> equality ignore case Java Set <String>相等忽略大小写

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM