Volodymyr Levytskyi
Volodymyr Levytskyi

Reputation: 3432

How to match two or more spaces in java.util.Scanner?

I have row of numbers which should be splitted by space.

But space might be long or short or just single space.

I fail to write regex that would split numbers correctly . Here is my attempt:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String next = scanner.next();

    System.out.println("split=" + Arrays.toString(next.split("\\s{1,}")));
}

Help me to split by any number of spaces between figures.

EDIT: Here is one of rows which should be splitted to get array of integers:

108 125 145  48  49  77  65  62  93 121 114 148 134 129 170 

My attempts were

inputScanner.nextLine().split("\\s{1,}");

Thanks!

Upvotes: 0

Views: 334

Answers (3)

Pshemo
Pshemo

Reputation: 124265

It seems that you can solve your problem easily using List<Integer>

List<Integer> myList = new ArrayList<>();
while (scanner.hasNextInt()) {
    myList.add(scanner.nextInt());
}

and later if you really need Integer[] array you can create one with

Integer[] array = myList.toArray(new Integer[myList.size()]);

Upvotes: 2

Paul Samsotha
Paul Samsotha

Reputation: 209052

Use split("\\s+"); for one or more spaces.

And why do you need to split if you're just getting the next token from the scanner?

String next = scanner.next();

Maybe you want

String next = scanner.nextLine();

System.out.println("split=" + Arrays.toString(next.split("\\s+")));

If you want to get the Integer values of an entire line you can do this

String[] numString = next.split("\\s+");
int[] nums = new int[numString.length];

for (int i = 0; i < numString.length; i++){
    nums[i] = Integer.parseInt(numString[i].trim());
}

System.out.println(Arrays.toString(nums));

Upvotes: 2

Masudul
Masudul

Reputation: 21971

To match at least 2 or more spaces use regex \s{2,}

System.out.println("split=" + Arrays.toString(next.split("\\s{2,}")));

Upvotes: 0

Related Questions