在java中,我想逐行读取文件并将该行打印到输出。 我想用正则表达式解决这个问题。
while (...)
{
private static java.util.regex.Pattern line = java.util.regex.Pattern.compile(".*\\n");
System.out.print(scanner.next(line));
}
代码中的正则表达式不正确,因为我得到了InputMismatchException。 我正在研究这个正则表达式 2 个小时。请帮忙解决。
使用正则表达式 powertoy,我发现“.*\n”是正确的。但我的程序运行不正确。
整个来源是:
/**
* Extracts the points in the standard input in off file format to the standard output in ascii points format.
*/
import java.util.regex.Pattern;
import java.util.Scanner;
class off_to_ascii_points
{
private static Scanner scanner = new Scanner(System.in);
private static Pattern fat_word_pattern = Pattern.compile("\\s*\\S*\\s*");
private static Pattern line = Pattern.compile(".*\\n", Pattern.MULTILINE);
public static void main(String[] args)
{
try
{
scanner.useLocale(java.util.Locale.US);
/* skip to the number of points */
scanner.skip(fat_word_pattern);
int n_points = scanner.nextInt();
/* skip the rest of the 2. line */
scanner.skip(fat_word_pattern); scanner.skip(fat_word_pattern);
for (int i = 0; i < n_points; ++i)
{
System.out.print(scanner.next(line));
/*
Here my mistake is.
next() reads only until the delimiter,
which is by default any white-space-sequence.
That is next() does not read till the end of the line
what i wanted.
Changing "next(line)" to "nextLine()" solves the problem.
Also, setting the delimiter to line_separator
right before the loop solves the problem too.
*/
}
}
catch(java.lang.Exception e)
{
System.err.println("exception");
e.printStackTrace();
}
}
}
示例输入的开头是:
OFF
4999996 10000000 0
-28.6663 -11.3788 -58.8252
-28.5917 -11.329 -58.8287
-28.5103 -11.4786 -58.8651
-28.8888 -11.7784 -58.9071
-29.6105 -11.2297 -58.6101
-29.1189 -11.429 -58.7828
-29.4967 -11.7289 -58.787
-29.1581 -11.8285 -58.8766
-30.0735 -11.6798 -58.5941
-29.9395 -11.2302 -58.4986
-29.7318 -11.5794 -58.6753
-29.0862 -11.1293 -58.7048
-30.2359 -11.6801 -58.5331
-30.2021 -11.3805 -58.4527
-30.3594 -11.3808 -58.3798
我首先跳到数字 4999996,这是包含点坐标的行数。这些行是我试图写入输出的内容。
最佳答案
我建议使用
private static Pattern line = Pattern.compile(".*");
scanner.useDelimiter("[\\r\\n]+"); // Insert right before the for-loop
System.out.println(scanner.next(line)); //Replace print with println
为什么您的代码无法按预期工作:
这与您使用的 Scanner 类以及该类的工作方式有关。
javadoc 指出:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
这意味着当您调用 Scanner 的 .next* 方法之一时,扫描器将读取指定的输入,直到遇到下一个分隔符。
因此,您对 scanner.next(line)
的第一次调用开始读取以下行
-28.6663 -11.3788 -58.8252
并停在 -28.6663 之后的空格处。然后它检查 token (-28.6663) 是否与您提供的模式 (.*\n) 匹配,而该模式显然不匹配 (-28.6663)。这就是原因。
关于java正则表达式行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1012367/