2

I have a txt file which has several rows like this

7. SSWAB        38    15   -  57    

but I don't need all the values, just the String and the integers. I would use nextInt for the Integers, but how can I deal with 1. and -?

Also there is the string, what is a useful nextString? Is next enough?

I have tried something like this, just using tokens, but nothing happens

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
vszholobov
  • 2,133
  • 1
  • 8
  • 23
redbite
  • 189
  • 1
  • 2
  • 10

1 Answers1

2

You can use scanner.next(Pattern pattern) for matching these groups.

Try this regex

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

Demo
It would catch all groups you mentioned plus fractional numbers and negative numbers.

Then you can use this regex in scanner

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();
    }
}

This code catch all matching groups and skip others.

Output

7.
SSWAB
38
15
57
vszholobov
  • 2,133
  • 1
  • 8
  • 23