简体   繁体   English

正则表达式与文件名末尾不匹配

[英]Regex not matching the end of a filename

I need to filter out the files in a directory that end with "_done". 我需要过滤出以“ _done”结尾的目录中的文件。
The directory contains three .txt files, namely format1.txt , format2.txt and format2_done.txt that needs to be filtered out. 该目录包含三个.txt文件,即需要过滤掉的format1.txtformat2.txtformat2_done.txt

The following sample correctly lists all the files: 下面的示例正确列出了所有文件:

System.out.println("all files: ");
String[] files = folder.list();
for (String item : files) {
    System.out.println(item);
}

Output: 输出:

all files: 
format1.txt
format2.txt
format2_done.txt

But the following sample: 但是以下示例:

System.out.println("filtered: ");
String[] filteredFiles = folder.list((File folder, String name) 
                         -> {return !(name.matches("_done.txt>"));});

for (String item : filteredFiles) {
    System.out.println(item);
}

produces the same output and doesn't filter anything: 产生相同的输出,不过滤任何内容:

filtered: 
format1.txt
format2.txt
format2_done.txt

What am I doing wrong? 我究竟做错了什么?

Try to use this regex instead .*_done\\\\.txt$ like this : 尝试改用此正则表达式.*_done\\\\.txt$如下所示:

String[] filteredFiles = folder.list((File folder, String name)
        -> !name.matches(".*_done\\.txt$")
);

details : 细节 :

  • .* zero or more character .*零个或多个字符
  • followed by _done\\\\.txt , note that you should to escape the dot with \\\\ 后面跟着_done\\\\.txt ,请注意,您应使用\\\\转义点
  • $ end anchor $结束锚

Or you can just use String::endsWith : 或者,您可以只使用String :: endsWith

String[] filteredFiles = folder.list((File folder, String name)
        -> !name.endsWith("_done.txt")
);

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

相关问题 在正则表达式中匹配单词与句点结尾 - Matching word with period at end in regex 用于匹配具有非法文件名字符的字符串的正则表达式 - regex for matching strings that have illegal filename characters Java 正则表达式模式不适用于文件名匹配 - Java Regex pattern not working for filename matching 当开头或结尾为空时,正则表达式不匹配 - Regex not matching when the start or end are empty 用正则表达式检测字符串的第一个匹配结尾的问题 - issue to detect first matching end of string with regex 用于匹配“=”和“/”或“=”和字符串结尾之间的字符串的正则表达式 - Regex for matching strings between '=' and '/' or "=" and end of string 如何有效地测试目录中是否存在具有匹配文件名(正则表达式或通配符)的文件? - How to efficiently test if files with a matching filename (regex or wildcard) exists in a directory? 用`regex`匹配字符串末尾的电话号码,并返回两个部分 - Matching a phone number at the end of a string with `regex`, and return both parts 使用正则表达式在匹配字符串之前或结尾插入字符串 - Insert a string before a matching string or at the end using regex 正则表达式匹配所有内容,直到您不需要在行尾使用逗号 - Regex matching everything until you dont need a comma at end of line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM