java - 我如何在我的 Java 程序中使用 RegExp?

标签 java regex

我有以下字符串示例:

00001 1 12 123
00002 3 7 321
00003 99 23 332
00004 192 50 912

在单独的文本文件中。 数字由制表符而不是空格分隔。

我尝试读取文件并打印每一行(如果它与给定的 RegExp 匹配),但我找不到适合这些行的 RegExp。

private static void readFile() {
    String      fileName = "processes.lst";
    FileReader  file = null;
    String      result = "";


    try {
        file = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(file);

        String line = null;
        String regEx = "[0-9]\t[0-9]\t[0-9]\t[0-9]";
        while((line = reader.readLine()) != null)  {
            if(line.matches(regEx)) {
                result += "\n" + line;
            }
        }
    } catch(Exception e) {
        System.out.println(e.getMessage());
    } finally {
        if(file != null)
            try {
                file.close();
            } catch(Exception e) {
                System.out.println(e.getMessage());
            }
    }

    System.out.println(result);
}

我最终没有打印任何字符串!!

最佳答案

问题是 [0-9] 正好匹配一个数字,但您的输入通常在 TAB 字符之间有多个数字。您需要使用 [0-9]+ 来匹配每个数字。 (+ 表示前一个...的一次或多次重复)

但更简单的解决方案是使用 String.split(...) ...阅读 javadoc。

关于java - 我如何在我的 Java 程序中使用 RegExp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13639902/

相关文章:

java - 持久性单元 : jpaData - Unable to build EntityManagerFactory

python 如何让 re 忽略原始文本中的括号

php - 我不明白这个 Textile Regex

javascript - 删除逗号分隔字符串末尾和开头的空格和逗号

java - 尽管 jar 已正确添加到项目路径,但出现异常

java - 递归在应该为真时返回假

java - 使用没有 "injects"指令的 Dagger 模块

java - 如何让 Java 在拆分时忽略字符串中的空格数?

python - 如何优化这个正则表达式模式

java - 正则表达式通配符匹配