Ozymandias
Ozymandias

Reputation: 166

Extracting numbers from a string while keeping spaces

Given a string, I want to extract the numbers and keep a spacing between them. The procedure for this generally involves removing all spacing so that 12 3 becomes 123 which I'm avoiding.

For example if the input is 17/(2 + 3)-13 I want 17 2 3 13.

I also have methods that extract the operators and parenthesis in between them but I can't separate the numbers greater than 9.

Here's my attempt which produces out of bounds exceptions

 public static void partition(){
     String word = "123 -asdfqwerty- 45";
     String kajigger = "";

     for(int i = 0; i < word.length(); i++){
         char c = word.charAt(i);
         if(Character.isDigit(c)){
             int j = i;
             while(Character.isDigit(word.charAt(j))){
                 kajigger += word.charAt(j);
                 j++;
             }
             }
         }
     System.out.println(kajigger);
 }

In this example I wanted the output 123 45

The general idea is converting from infix to postfix by moving all numbers the the left and operators to the right.

Upvotes: 0

Views: 569

Answers (1)

azro
azro

Reputation: 54148

You go by this way :

  • replace all multiple following (+) chars which are non-digits (\D) by a single space (" ")
  • so \D+ changes 7/(2 + 3)-13 into 7 2 3 13

String str = "17/(2 + 3)-13";
str = str.replaceAll("\\D+", " ");
System.out.println(str);   // 17 2 3 13

Regex demo

Upvotes: 3

Related Questions