【问题标题】:txt file with integers, strings and bulleted list (1.)带有整数、字符串和项目符号列表的 txt 文件 (1.)
【发布时间】:2021-10-27 00:13:28
【问题描述】:

我有一个 txt 文件,里面有几行这样的

7. SSWAB        38    15   -  57    

但我不需要所有的值,只需要字符串和整数。 我会使用 nextInt 作为整数,但我该如何处理 1. 和 -?

还有字符串,什么是有用的nextStringnext够了吗?

我尝试过这样的事情,只是使用令牌,但没有任何反应

scanner.next(); //7.
String  s = (scanner.next()); //SAVES sswab
Integer n1 = scanner.nextInt(); //38
Integer n2 = scanner.nextInt(); //15
Integer n3 = scanner.nextInt(); //- is skipped, as next int is 57

【问题讨论】:

    标签: java file io txt


    【解决方案1】:

    您可以使用scanner.next(Pattern pattern) 来匹配这些组。

    试试这个正则表达式

    -?\d+\.?(\d+)?|\w+
    

    Demo
    它会捕获您提到的所有组以及小数和负数。

    然后你可以在扫描仪中使用这个正则表达式

    String text = "7. SSWAB        38    15   -  57    ";
    Scanner scanner = new Scanner(text);
    while(scanner.hasNext()) {
        if(scanner.hasNext("-?\\d+\\.?(\\d+)?|\\w+")) {
            System.out.println(scanner.next("-?\\d+\\.?(\\d+)?|\\w+"));
        } else {
            scanner.next();
        }
    }
    

    此代码捕获所有匹配组并跳过其他组。

    输出

    7.
    SSWAB
    38
    15
    57
    

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 2019-08-05
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多