【问题标题】:Extracting a value from a file name base on regex in Java基于Java中的正则表达式从文件名中提取值
【发布时间】:2015-11-05 16:33:59
【问题描述】:

假设我的文件名模式类似于 %#_Report_%$_for_%&.xls%#%$ 正则表达式可以有任何字符,但 %& 是一个日期。

现在我如何才能在 java 中获取文件名上这些正则表达式的实际值。

例如如果实际文件名是Genr_Report_123_for_20151105.xls如何获取

%# value is Genr
%$ value is 123
%& value is 20151105

【问题讨论】:

  • 文件正则表达式为 %#_Report_%$_for_%&.xls
  • 使用"^([^_]+)_Report_([^_]+)_for_([^._]+)\.xls$" 并使用捕获组。
  • 你能帮我写代码吗
  • 我会问你尝试了什么,但似乎明确的答案是什么。 @anubhava has given you the answer。如果您尝试实施但不起作用,请将其发布在问题中,我会帮助您。
  • 我已经尝试过匹配器和模式,但我无法找到解决方案

标签: java regex filenames


【解决方案1】:

你可以这样做:

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

public class Rgx {

    private String str1 = "", str2 = "", date = "";

    public static void main(String[] args) {
        String fileName = "Genr_Report_123_for_20151105.xls";

        Rgx rgx = new Rgx();
        rgx.extractValues(fileName);
        System.out.println(rgx.str1 + " " + rgx.str2 + " " + rgx.date);
    }

    private void extractValues(String fileName) {
        Pattern pat = Pattern.compile("([^_]+)_Report_([^_]+)_for_([\\d]+)\\.xls");
        Matcher m = pat.matcher(fileName);

        if (m.find()) {
            str1 = m.group(1);
            str2 = m.group(2);
            date = m.group(3);
        }
    }
}

【讨论】:

  • 感谢您的回复,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 2018-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多