我正在尝试制作一个小程序,该程序将从文件中读取输入,并在它们与特定格式匹配时将其打印出来:
Team Name : Another Team name : Score : Score
这是我到目前为止所做的,如果您能指出我正确的方向,我将非常感激
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Generator {
public static void main(String[] args) throws FileNotFoundException{
String file;
Scanner fileScan;
fileScan = new Scanner (new File("document.txt"));
int count = 0;
while (fileScan.hasNextLine()){
file = fileScan.nextLine();
System.out.println(file);
count++;
}
System.out.println(count+ " number of lines successfully validated");
}
}
我希望程序验证格式是否有效,如果无效,则不打印该行,而是对其进行计数,以便我可以在最后输出有多少行未正确验证。
谢谢。
最佳答案
使用String.matches(regexPattern)
进行非常简单的检查。使用另一个变量来记录无效行的计数。
int invalidLines = 0;
String line =null;
while (fileScan.hasNextLine()){
line = fileScan.nextLine();
if(!line.matches(regexPattern)){
invalidLines++;
}
count++;
}
使用 \w+
进行单词匹配,使用 \d+
进行数字匹配。
关于java - 扫描仪文件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26677289/