Java 如何从文本文件中跳过某些输入

Java 如何从文本文件中跳过某些输入,java,file-io,filter,Java,File Io,Filter,我正在尝试接收一个如下所示的文件(但还有数百行): 123000个“带空格的单词”每行都不一样。我只是想把它作为我需要的占位符来显示 如果我只需要得到每行的123,我怎么能忽略其中的其他东西呢 以下是我尝试过的: File file = new File("txt file here"); try (Scanner in = new Scanner(file)) { int count = 0; while (in.hasNext())

我正在尝试接收一个如下所示的文件(但还有数百行):

123000个“带空格的单词”每行都不一样。我只是想把它作为我需要的占位符来显示

如果我只需要得到每行的123,我怎么能忽略其中的其他东西呢

以下是我尝试过的:

  File file = new File("txt file here"); 
   try (Scanner in = new Scanner(file))
     {
         int count = 0;
         while (in.hasNext())
         {
             int a = in.nextInt();
             String trash1 = in.next();
             String trash2 = in.next();
             String trash3 = in.next();
             int b = in.nextInt();
             int c = in.nextInt();
             int d = in.nextInt();
             //This continues but I realize this will eventually throw an
             //exception at some points in the text file because 
             //some rows will have more "words with spaces" than others
         }
     }
     catch (FileNotFoundException fnf)
     {
         System.out.println(fnf.getMessage());
     }

有没有办法跳过“000”和“带空格的单词”之类的东西,而我只接受“123”呢?或者我只是用一种“坏”的方式来处理这个问题。谢谢

逐行抓取,并围绕一个空格拆分该行,然后在字符串数组上迭代,只考虑数组中的字符串是否与您想要的匹配

int countsOf123s = 0;
while (in.hasNextLine())
{
    String[] words = in.nextLine().split(" "); //or for any whitespace do \\s+
    for(String singleWord : words)
    {
        if(singleWord.equals("123"))
        {
            //do something
            countsOf123s++;
        }
    }
}

您可以使用正则表达式剥离行的第一部分

String cleaned = in.nextLine().replace("^(\\d+\\s+)+([a-zA-Z]+\\s+)+", "");
^
表示模式从文本开头(行首)开始

(\\d+\\s+)
匹配一组或多组后跟空格的数字

([a-zA-Z]+\\s+
匹配一组或多组字母字符,后跟空格

如果有标点符号或其他字符,您可能必须修改模式。如果您不熟悉使用正则表达式,可以阅读更多有关正则表达式的内容

String cleaned = in.nextLine().replace("^(\\d+\\s+)+([a-zA-Z]+\\s+)+", "");