【问题标题】:Extracting number from a formatted text file Java从格式化的文本文件Java中提取数字
【发布时间】:2016-07-20 16:56:21
【问题描述】:

我有一个文本文件,其中包含几行字符串,后跟两个数字,用冒号分隔。例如:

...................
words 1:1
morewords 2:1
something 3:1
else 4:2
elsewhere 5:2
....................
middleItem 313 : 60
middleOther 314 : 60
......................
secondToLast 138714 : 29698
last 138715 : 29698
.......................

我希望能够提取冒号左右两侧的数字,并能够将它们读取为整数。我需要能够使用这些 int 数字稍后执行计算,因此将它们作为字符串读取将无济于事。

我尝试过使用子字符串和正则表达式,但无法找到正确的方法。任何提示都会有所帮助!

【问题讨论】:

  • 这个正则表达式非常简单。展示你的尝试。
  • 发布你到目前为止所尝试的内容。
  • 我用 sc.findInLine("[0-9]");但有时字符串项本身存在数字,导致变量赋值错误。

标签: java string file-io int


【解决方案1】:
Scanner sc = new Scanner(<OUR_FILE>)
sc.nextInt()

【讨论】:

    【解决方案2】:
    Scanner s = new Scanner("file"); // A delimiter can also be used to separate lines
    while (s.hasNext()) {
        if (s.hasNextInt()) { 
            int a = (s.nextInt()); //  found integer
        } else {
            s.next(); // read the next token
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用流创建映射,将每个单词映射到Pair&lt;Integer, Integer&gt;

      Pattern p = Pattern.compile("^(\\w+)\\s+(\\d+)\\s*:\\s*(\\d+)$");
      
      Path input = Paths.get("input.txt");
      try(BufferedReader br = Files.newBufferedReader(input)) {
          Map<String, Pair<Integer, Integer>> map
              = br.lines() // Get Stream of lines
                  .map(String::trim) // Safety trim
                  .map(p::matcher) // Get mathcer for each line
                  .filter(Matcher::find) // Filter on lines that match
                  .collect( // Collect into map
                      Collectors.toMap(
                          m -> m.group(1), // The word is the key
                          // Maps to a Pair of the 2 integers
                          m -> new Pair<>(Integer.valueOf(m.group(2)), Integer.valueOf(m.group(3)))
                      )
                  );
      
          /* Usage */
          Pair<Integer, Integer> pair = map.get("middleItem");
          System.out.println(pair.getKey()); // 313
          System.out.println(pair.getValue()); // 60
      } catch(IOException e) {
          e.printStackTrace();
      }
      

      注意:正则表达式不是我的专长,所以可能会有更好的模式。

      【讨论】:

        【解决方案4】:

        我确信有更好的方法,但我首先想到的是使用

        scanner.nextInt() = variable1, 
        scanner.nextInt() = variable2 
        

        等等。然后,使用您分配的变量写出所有逻辑和计算。

        这样做(结合poorvankBhatia的回答)应该可以让您使用整个文档。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-27
          • 1970-01-01
          • 1970-01-01
          • 2013-08-03
          • 2017-08-06
          • 1970-01-01
          • 2023-03-31
          • 1970-01-01
          相关资源
          最近更新 更多