Java 文件扩展名正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/234249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:33:09  来源:igfitidea点击:

Java file extension regex

javaregex

提问by Dónal

I'm trying to come up with a Java regex that will match a filename only if it has a valid extension. For example it should match "foo.bar" and "foo.b", but neither "foo." nor "foo".

我正在尝试提出一个 Java 正则表达式,它仅在具有有效扩展名时才匹配文件名。例如,它应该匹配“foo.bar”和“foo.b”,但都不匹配“foo”。也不是“富”。

I've written the following test program

我编写了以下测试程序

public static void main(String[] args) {
  Pattern fileExtensionPattern = Pattern.compile("\.\w+\z");

  boolean one = fileExtensionPattern.matcher("foo.bar").matches();
  boolean two = fileExtensionPattern.matcher("foo.b").matches();
  boolean three = fileExtensionPattern.matcher("foo.").matches();
  boolean four = fileExtensionPattern.matcher("foo").matches();

  System.out.println(one + " " + two + " " + three + " " + four);
}

I expect this to print "true true false false", but instead it prints false for all 4 cases. Where am I going wrong?

我希望这会打印“真真假假”,但它会为所有 4 种情况打印假。我哪里错了?

Cheers, Don

干杯,唐

回答by Adam Rosenfield

The Matcher.matches()function tries to match the pattern against the entire input. Thus, you have to add .*to the beginning of your regex (and the \\Zat the end is superfluous, too), or use the find()method.

所述Matcher.matches()函数尝试匹配针对整个输入的模式。因此,您必须添加.*到正则表达式的开头(\\Z结尾也是多余的),或者使用find()方法。

回答by Bill K

public boolean isFilename(String filename) {
    int i=filename.lastInstanceOf(".");
    return(i != -1 && i != filename.length - 1)
}

Would be significantly faster and regardless of what you do, putting it in a method would be more readable.

会明显更快,无论您做什么,将其放入方法中都会更具可读性。

回答by hanisa

package regularexpression;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularFile {
    public static void main(String[] args) {
        new RegularFile();
    }

    public RegularFile() {

        String fileName = null;
        boolean bName = false;
        int iCount = 0;
        File dir = new File("C:/regularfolder");
        File[] files = dir.listFiles();
        System.out.println("List Of Files ::");

        for (File f : files) {

            fileName = f.getName();
            System.out.println(fileName);

            Pattern uName = Pattern.compile(".*l.zip.*");
            Matcher mUname = uName.matcher(fileName);
            bName = mUname.matches();
            if (bName) {
                iCount++;

            }
        }
        System.out.println("File Count In Folder ::" + iCount);

    }
}