我正在打印txt文件的内容,同时跳过该文件中的任何数字。

我正在使用的文件如下所示:

一二三三四

五六七八

我曾尝试在System.out.print(token)之后使用input2.next()或input2.nextline(),但我遇到错误或无法准确读取下一行。

import java.util.*;
import java.io.*;


public class ScannerClass {


public static void main(String[] args) throws FileNotFoundException {


    System.out.print("Enter file name and extension: ");

    Scanner input = new Scanner(System.in);

    File file = new File(input.next());

    Scanner input2 = new Scanner(file);


    String token;

//this will print out the first line in my txt file, I am having trouble
//reading the next line in the file!

    while ((token = input2.findInLine("[\\p{Alpha}\\p{javaWhitespace}]+")) != null) {
        System.out.print(token);


    }

  }
}


输出为:

一二三四

我想看到的是整个txt文件减去任何数字,例如:

一二三四

五六八

最佳答案

reg exp的一个主要问题是,它只匹配行的一部分,首先匹配数字,然后匹配数字,而findInLine则以某种方式使行计数器前进。

因此,这是使用您的reg exp模式的另一种解决方案,但我已将文件中的读数与匹配逻辑分开了

Pattern p = java.util.regex.Pattern.compile("[\\p{Alpha}\\p{javaWhitespace}]+");
while (input2.hasNextLine()) {
    String line = input2.nextLine();
    Matcher m = p.matcher(line);
    while (m.find()) {
        System.out.print(m.group()); //Prints each found group
    }
    System.out.println();
}

07-28 02:14
查看更多