[英]How I use RegExp in my Java program?
我有以下字符串示例:
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。
使用此String regEx = "[0-9]+\\s[0-9]+\\s[0-9]+\\s[0-9]+";
{2,3}至少2個字符,最多3個字符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.