Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract doubles or integers from a string java

Tags:

java

string

regex

Im writing this code in which the user enters a string which contains numbers, e.g.

H3.07LLo my nam3 is bob12

And the output should be

3.07, 3.0, 12.0

I've managed to get a regular expression 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'm pretty new to regex. I tried adding |[0-9]| but I keep on messing it up wherever I put it in my current regex

like image 543
user3323950 Avatar asked Dec 27 '14 21:12

user3323950


People also ask

How do I extract an INT from a double in Java?

Double method intValue(). You can first use auto-boxing to convert double primitive to Double and then just call intValue() method, this will return an equivalent integer value, as shown below : Double d = 7.99; // 7 int i = d. intValue(); System.


3 Answers

You can do it in one line by replacing non-numeric characters with space, trimming then splitting on space.

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

That gives you the parts of the input that are numbers. If you then actually need doubles:

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

For some java 8 fun, the whole thing can be done in one line!

double[] nums = Arrays.stream(str.replaceAll("[^0-9.]+", " ").trim().split(" ")).mapToDouble(Double::parseDouble).toArray();
like image 98
Bohemian Avatar answered Oct 22 '22 02:10

Bohemian


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

like image 3
Enissay Avatar answered Oct 22 '22 03:10

Enissay


There is one problem in your regex which is using the dot (.) character to match the literal dot. The dot character is a special symbol in regex terminology that matches any character. In order to only match the decimal point ., you need to escape it using \..

To match an integer, you could make the group consisting of the decimal point and the fractional digits to be optional, using the question mark symbol. There is also no need for parentheses unless you're grouping patterns. So your regex could be simply -?(\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()));
}

Output:

3.07
3.0
12.0
like image 1
M A Avatar answered Oct 22 '22 04:10

M A