Java 在 .txt 文件中搜索不同格式(100,50 或 100.50)的给定数字
Java Search a .txt file for a given number with different format (100,50 or 100.50)
我想在给定的 txt 文件中搜索一个数字和 return 找到它的行。这个数字可以有不同的格式。它可以用 , 或 来写。或者完全不同的东西。我知道输入的数字总是这样:100.50; 3424.00; 0.12 ...
我当前的代码只有在一行中没有其他字符时才会检测到这些数字。
该代码将数字分为两部分(100.50 -> 前面:100 和后面:50)。然后我添加通配符“。”并使用方法 matches(front + "." + back)
如果数字不只是数字,我如何才能找到它?
感谢您的帮助!
private static int searchTotal(String pictureID, String value) throws IOException {
int counter = 0;
String front = value.substring(0, value.length() - 3); //dividing the value into 100,50 -> 100 and 50
String back = value.substring(value.length() - 2);
BufferedReader br = new BufferedReader(
new FileReader(pathTXTFiles + "/" + pictureID +".txt")); //input txt
String s;
while ((s = br.readLine()) != null) {
counter++;
if (s.matches(front + "." + back)) { //searching with the wildcard
return counter; //counter gives me the line of the searched number
}
}
return 0;
}
您必须在前后允许其他字符:
s.matches(".*"+front + "[.,]" + back+".*");
否则 matches
仅当该行仅包含一个十进制数时才 return 为真。
我想在给定的 txt 文件中搜索一个数字和 return 找到它的行。这个数字可以有不同的格式。它可以用 , 或 来写。或者完全不同的东西。我知道输入的数字总是这样:100.50; 3424.00; 0.12 ...
我当前的代码只有在一行中没有其他字符时才会检测到这些数字。 该代码将数字分为两部分(100.50 -> 前面:100 和后面:50)。然后我添加通配符“。”并使用方法 matches(front + "." + back)
如果数字不只是数字,我如何才能找到它?
感谢您的帮助!
private static int searchTotal(String pictureID, String value) throws IOException {
int counter = 0;
String front = value.substring(0, value.length() - 3); //dividing the value into 100,50 -> 100 and 50
String back = value.substring(value.length() - 2);
BufferedReader br = new BufferedReader(
new FileReader(pathTXTFiles + "/" + pictureID +".txt")); //input txt
String s;
while ((s = br.readLine()) != null) {
counter++;
if (s.matches(front + "." + back)) { //searching with the wildcard
return counter; //counter gives me the line of the searched number
}
}
return 0;
}
您必须在前后允许其他字符:
s.matches(".*"+front + "[.,]" + back+".*");
否则 matches
仅当该行仅包含一个十进制数时才 return 为真。