Java 扫描程序文件验证
我正在尝试制作一个小程序,它将从文件中读取输入,并在符合特定格式时打印出来,即:Java 扫描程序文件验证,java,regex,validation,Java,Regex,Validation,我正在尝试制作一个小程序,它将从文件中读取输入,并在符合特定格式时打印出来,即: Team Name : Another Team name : Score : Score 这是我到目前为止所做的,如果你能给我指出正确的方向,我将非常感激 import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class Generator { public static
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");
}
}
我希望程序验证格式是否有效,如果无效,请不要打印该行,但要对其进行计数,以便在最后输出未正确验证的行数
谢谢。和数组的length
属性是这里要使用的工具
我留给您去了解如何正确使用它们。使用
String.matches(regexpatern)
进行检查非常简单。使用另一个变量保持无效行的计数
int invalidLines = 0;
String line =null;
while (fileScan.hasNextLine()){
line = fileScan.nextLine();
if(!line.matches(regexPattern)){
invalidLines++;
}
count++;
}
使用\w+
进行单词匹配,使用\d+
进行数字匹配
公共静态void main(字符串[]args)抛出FileNotFoundException{
int invalidcount=0;
字符串文件;
扫描仪文件扫描;
fileScan=新扫描仪(新文件(“document.txt”);
整数计数=0;
字符串arrTeam[]={“”“”};//创建包含有效输入的arrTeam数组
while(fileScan.hasNextLine()){
file=fileScan.nextLine();
对于(inti=0;i您可以使用regex匹配您的输入,如果它返回true,那么您的输入匹配;如果返回false,那么它不匹配Ex
String test = "TeamA:TeamB:44:99";
System.out.println("" + test.matches("\\D+[:]\\D+[:]\\d+[:]\\d+"));
这将匹配非数字:非数字:数字:数字您期望的有效输入是什么其他团队名称也可以是多个单词。
String test = "TeamA:TeamB:44:99";
System.out.println("" + test.matches("\\D+[:]\\D+[:]\\d+[:]\\d+"));