if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3})")){
Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}
A possible way of doing it:
Then you can run the following test:I think what you want (following from the direction you were going) is this:.[a-zA-Z]{3}
At the end, I have a conditional statement. It has to either match the end of the string (.txt(\.gz)
if(fileName.matches("([\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}).txt(\.gz)?")){
Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}
) OR it has to match a literal dot followed by 2 letters (, because in regex
^[\w-]+\d{2}-\d{2}-\d{4}\.txt(?:\.gz)?$
means "match any character".
^,$
我正试图创建一个正则表达式,以 "abcd_04-04-2020.txt "或 "abcd_04-04-2020.txt.gz "为名的文件。
[\w-]+
如何处理扩展的 "OR "条件。这是我目前所掌握的情况
\d{}
这只处理.txt.gz。我如何处理".txt.gz "谢谢
(?:\.gz)?
.gz
我正试图创建一个正则表达式,该表达式接收一个名为 "abcd_04-04-2020.txt "或 "abcd_04-04-2020.txt.gz "的文件,我如何处理扩展名的 "OR "条件。这是我有这么...你可以替换为|
与
你可以使用下面的regex来达到你的目的。以上字串的解释。
]
import java.util.regex.*;
public class Main
{
private static final Pattern pattern = Pattern.compile("^[\\w-]+\\d{2}-\\d{2}-\\d{4}\\.txt(?:\\.gz)?$", Pattern.MULTILINE);
public static void main(String[] args) {
String testString = "abcd_04-04-2020.txt\nabcd_04-04-2020.txt.gz\nsomethibsnfkns_05-06-2020.txt\n.txt.gz";
Matcher matcher = pattern.matcher(testString);
while(matcher.find()){
System.out.println(matcher.group(0));
}
}
}
- 匹配测试字符串的开头和结尾。 - 匹配一个或多个连字符的单词字符。
遍 交替(或如你所料 endsWith
或
if(fileName.endsWith(".txt") || fileName.endsWith(".txt.gz")){
Pattern.compile("[._]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.");
}
),但这也更清晰,更有效。这里。
(.[a-zA-Z]{2})?
JAVA中的实现。
([\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}.[a-zA-Z]{3}(.[a-zA-Z]{2})?)
你可以在java中找到上述regex的实现,在 请注意,如果您也想匹配有效的日期,请访问这里。
Pattern pattern = Pattern.compile("^[\\w._-]+_\\d{2}-\\d{2}-\\d{4}(\\.txt(\\.gz)?)$");
如果您想匹配有效日期,请访问
String[] fileNames = {
"abcd_04-04-2020.txt",
"abcd_04-04-2020.tar",
"abcd_04-04-2020.txt.gz",
"abcd_04-04-2020.png",
".txt",
".txt.gz",
"04-04-2020.txt"
};
Arrays.stream(fileNames)
.filter(fileName -> pattern.matcher(fileName).find())
.forEach(System.out::println);
// output
// abcd_04-04-2020.txt
// abcd_04-04-2020.txt.gz
这个。
[\\w._-]+[0-9]{2}-[0-9]{2}-[0-9]{4}\\.[a-zA-Z]{3}(?:$|\\.[a-zA-Z]{2}$)
为什么不直接使用 $
而不是繁体字\\.[a-zA-Z]{2}
.
.
你所需要的工作