For example, there is a line - "I bought 10 bananas spent 5 rubles." A string can change the number of words, the number itself, but the number of numeric values ​​is always the same.

How to bring individually all the numeric values ​​from a string into an array?

Tell me how to solve.

    3 answers 3

    Search for groups of numbers in a string and add them to the list:

    String str = "abc 10 def ghi 5 jkl"; Pattern pattern = Pattern.compile("(\\d+)"); Matcher matcher = pattern.matcher(str); List<String> matches = new ArrayList<>(); while (matcher.find()) { matches.add(matcher.group(1)); } 
    • Capturing a group is optional. You can simply match on "\\ d +" and then group(0) will give the same result. - Agrgg
    • @Agrgg then it’s possible to write group() instead of group(0) - save one character. Yes, in this case, group(0) will give the same result as group(1) , but using group(0) to capture the first group can eventually go sideways. - Regent
    • Guys, there was a problem - if the number is not an integer, for example, 3.14, then the regulars breaks it into 3 and 14, what should be? - evb
    • one
      @evb if you just need a positive fractional number through a dot, then a regular expression will do: (\\d+(\\.\\d+)?) . It is suitable for both integers and fractional ones, so that you can easily replace the expression presented in the answer for this. If you need for more complex cases (sign, degree, etc.), then this is worth asking a separate question. - Regent
    • @Regent Don't tell me, groups in regular expressions affect not only the number of characters, but also the performance. Of course, in such a simple case, the influence is negligible, but as a general rule, groups should not be abused. - Agrgg

    I am far from Java, but is it not possible to iterate a string and check if the character is not numeric ? If it is - to an array (or to a structure more suitable for the task)

      You can use regular expressions. Declare a pattern that searches for numeric groups, apply it to the input string, and then go through all the groups. Like that:

       String line = "Купил 10 бананов потратил 5 рублей"; Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(line); while (matcher.find()) { //Здесь matcher.group(0) -- это будет найденное число в строковом виде System.out.println("Found: " + matcher.group(0)); } 

      The code above should output:

       Found: 10 Found: 5 

      More information about regular expressions is written here , a similar question, only with the words here.