[英]How I use RegExp in my Java program?
I have the following string examples: 我有以下字符串示例:
00001 1 12 123
00002 3 7 321
00003 99 23 332
00004 192 50 912
In a separate text file. 在单独的文本文件中。 Numbers are separated by tabs not spaces.
数字由制表符而不是空格分隔。
I tried to read the file and print each line if it matches a given RegExp, but I could not find the suitable RegExp for these lines. 我尝试读取该文件并打印每行(如果它与给定的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);
}
I ended up without any string being printed!! 我最终没有打印任何字符串!
The problem is that [0-9]
matches exactly one digit, but your input often has multiple digits between the TAB characters. 问题是
[0-9]
恰好匹配一位数字,但是您的输入在TAB字符之间通常有多个数字。 You need to use [0-9]+
to match each number. 您需要使用
[0-9]+
来匹配每个数字。 (The +
means one or more repetitions of the previous ...) (
+
表示上一个...的一个或多个重复。)
But a simpler solution would be to use String.split(...)
... read the javadoc. 但是更简单的解决方案是使用
String.split(...)
...阅读javadoc。
use this String regEx = "[0-9]+\\s[0-9]+\\s[0-9]+\\s[0-9]+";
使用此
String regEx = "[0-9]+\\s[0-9]+\\s[0-9]+\\s[0-9]+";
{2,3} for minimum of 2 character & maximum 3 character {2,3}至少2个字符,最多3个字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.