我有以下字符串示例:
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/