Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all numbers in the String [closed]

For example, I have input String: "qwerty1qwerty2";

As Output I would like have [1,2].

My current implementation below:

import java.util.ArrayList;
import java.util.List;

public class Test1 {

    public static void main(String[] args) {
        String inputString = args[0];
        String digitStr = "";
        List<Integer> digits = new ArrayList<Integer>();

        for (int i = 0; i < inputString.length(); i++) {
            if (Character.isDigit(inputString.charAt(i))) {
                digitStr += inputString.charAt(i);
            } else {
                if (!digitStr.isEmpty()) {
                    digits.add(Integer.parseInt(digitStr));
                    digitStr = "";
                }
            }
        }
        if (!digitStr.isEmpty()) {
            digits.add(Integer.parseInt(digitStr));
            digitStr = "";
        }

        for (Integer i : digits) {
            System.out.println(i);
        }
    }
}

But after double check I dislake couple points:

  1. Some lines of code repeat twice.

  2. I use List. I think it is not very good idea, better using array.

So, What do you think?

Could you please provide any advice?

like image 500
user471011 Avatar asked Sep 10 '25 16:09

user471011


2 Answers

Use replaceAll:

String str = "qwerty1qwerty2";      
str = str.replaceAll("[^0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));

Output:

[1, 2]

[EDIT]

If you want to include - a.e minus, add -?:

String str = "qwerty-1qwerty-2 455 f0gfg 4";      
str = str.replaceAll("[^-?0-9]+", " "); 
System.out.println(Arrays.asList(str.trim().split(" ")));

Output:

[-1, -2, 455, 0, 4]

Description

[^-?0-9]+
  • + Between one and unlimited times, as many times as possible, giving back as needed
  • -? One of the characters “-?”
  • 0-9 A character in the range between “0” and “9”
like image 164
Maxim Shoustin Avatar answered Sep 12 '25 06:09

Maxim Shoustin


import java.util.regex.Matcher;
import java.util.regex.Pattern;

...

Pattern pattern = Pattern.compile("[0-9]+"); 
Matcher matcher = pattern.matcher("test1string1337thingie");

// Find all matches
while (matcher.find()) { 
  // Get the matching string  
  String match = matcher.group();
}

Is one regexp solution.

like image 22
Toni Avatar answered Sep 12 '25 06:09

Toni