【问题标题】:Regular expression pattern matching in Java [closed]Java中的正则表达式模式匹配[关闭]
【发布时间】:2012-10-11 11:08:05
【问题描述】:

请帮助我完成以下任务:

我在一个数组中有许多如下文件:

jack+0.txt
jack+2.txt
jack+4.txt
tim+0.txt
tim+2.txt
tim+4.txt
raph+0.txt
raph+2.txt
raph+4.txt
wells+0.txt
wells+2.txt
wells+4.txt
etc.

我想写一个程序来做以下事情:

if the filename is like *0.txt, a++;
if the filename is like *2.txt, b++;
if the filename is like *4.txt, c++;

需要的核心帮助是使用正则表达式(在 Java 中)。

【问题讨论】:

  • 谢谢大家,我正在尝试建议的方法,很快就会回来。

标签: java regex match filenames


【解决方案1】:

这个想法,如果你有少量不同的结局:

if (filename.endsWith("0.txt")) a++;

【讨论】:

  • 可能是最简单的方法
【解决方案2】:

我会在加号上做一个字符串拆分,然后检查第二部分。

String[] parts = s.split("+");
if (parts[1].equals("0.txt") {

} else // the rest of the tests

【讨论】:

    【解决方案3】:
    for (File file : files) {
        if (file.getName().matches(".*0[.]txt") {
            a++;
        } else if ...
    }
    

    【讨论】:

    • 谢谢大家,还有丹尼尔,我脱帽致敬。这个想法对我有用。非常感谢!
    【解决方案4】:

    这会从文件名中取出数字,然后你可以做一个 switch case

    string filename;
    
    int category = Integer.parseInt(filename.substring(filename.length() - 5, filename.length() - 4))
    

    【讨论】:

    • 如果文件将来有多个编号怎么办?
    猜你喜欢
    • 2016-04-24
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多