How to extract double or integer numbers from java string

Im writing this code into which the user enters a string containing numbers, for example.

H3.07LLo my nam3 is bob12

And the way out should be

3.07, 3.0, 12.0

I managed to get a regex to look for doubles, but I don't know how to look for ints. this is my regex:

(-)?(([^\\d])(0)|[1-9][0-9]*)(.)([0-9]+)

I am new to regex. I tried adding |[0-9]|, but I keep messing it up, wherever I put it in the current regex

+4
source share
3 answers

You can use:

(-?[0-9]+(?:[,.][0-9]+)?)

Explanation:

NODE                       EXPLANATION
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    -?                     '-' (optional (matching the most amount
                           possible))
--------------------------------------------------------------------------------
    [0-9]+                 any character of: '0' to '9' (1 or more
                           times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
    (?:                    group, but do not capture (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
      [,.]                 any character of: ',', '.'
--------------------------------------------------------------------------------
      [0-9]+               any character of: '0' to '9' (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
    )?                     end of grouping
--------------------------------------------------------------------------------
  )                        end of \1

DEMO

+3
source

, (.) . , . ., \..

, , , , . , . , -?(\d+)(\.\d+)?.

String input = "H3.07LLo my nam3 is bob12";
Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
    System.out.println(Double.valueOf(matcher.group()));
}

:

3.07
3.0
12.0
+1

, , , .

String[] numbers = str.replaceAll("[^0-9.]+", " ").trim().split(" ");

, . :

double[] ds = new double[numbers.length];
for (int i = 0; i < numbers.length; i++) { 
    ds[i] = Double.parseDouble(numbers[i]);
}

java 8 , !

double[] nums = Arrays.stream(str.replaceAll("[^0-9.]+", " ").trim().split(" ")).mapToDouble(Double::parseDouble).toArray();
+1

Source: https://habr.com/ru/post/1569162/


All Articles