包含整数、字符串和项目符号列表的 txt 文件 (1.)

txt file with integers, strings and bulleted list (1.)

我有一个 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

您可以使用 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