gpt4 book ai didi

java - 检查java中记录的模式

转载 作者:行者123 更新时间:2023-12-01 08:51:18 25 4
gpt4 key购买 nike

我有一个文本文件。文件中的每一行代表一条记录,其中有 'n' 个由 | 分隔的列。 (管道)字符。列值的类型为 int、字符串、日期、时间戳等。空字符串和空格也可以作为列值。

我仅验证列值的计数,不需要验证数据类型。

有效记录示例,每列 5 列:

1234|xyz|abc|2016-04-08 11:12:40|234
1235|efgh|abc|2016-04-09 11:25:40|
1236|efghij| ||

验证码:

boolean valid = true;
String line = buffReader.readLine();
String[] tokens = null;
while (line != null){
tokens = line.split("\\|");
if ((tokens.length==4 || tokens.length==5) && countPipes(line)==4){

} else {
valid = false;
break;
}
line = buffReader.readLine();
}

private int countPipes(String line){
int count = 0;
count = line.length() - line.replace("|", "").length();
return count;
}

我觉得代码还可以更好。有人可以告诉我如何改进这段代码吗?

最佳答案

嗯,您可以简单地检查线路中是否有四个管道。如果正好有四个管道,则有五列,其中可能为空(您允许)。

while (line != null) {
if ( countPipes(line) != 4 ) {
valid = false;
break;
}
line = buffReader.readLine();
}

现在您根本不需要拆分该行。

不过,关于拆分的说明。如果您使用带有两个参数的 split 并使用负数,则 split 也将包含空元素的条目。这是一个演示:

public class Test {

public static void main(String[] args) throws IOException {
String line = "A|B|||";

String[] zeroSplit = line.split("\\|");
String[] negativeSplit = line.split("\\|",-1);

System.out.println( "When split without parameter: " + zeroSplit.length );
System.out.println( "When split with negative parameter: " + negativeSplit.length );
}
}

这里的输出是:

When split without parameter: 2When split with negative parameter: 5

So in this case, you can check that your split is exactly of length 5, and get the same result.

while (line != null) {
if ( line.split("\\|",-1).length != 5 ) {
valid = false;
break;
}
line = buffReader.readLine();
}

关于java - 检查java中记录的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42386287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com