Home > OS >  Extract double from string
Extract double from string

Time:10-12

I have a string that is formatted like this inputString = "!Circle(1.234)"

How do I extract just the 1.234? I have tried:

double value = Double.parseDouble(inputString.(replaceAll("[^0-9]", "")));

but that would also remove the "."

Edit: Wonder if I have something like inputString = "!Rectangle(1.2,1.3)"

or

input String = "!Triangle(1.1,1.2,1.3)"

What do I need to do to extract the numbers first, before casting them as double?

CodePudding user response:

Exclude dot from your regex.

double value = Double.parseDouble(inputString.replaceAll("[^0-9.]", ""));

CodePudding user response:

Try this.

static Pattern DOUBLE_PATTERN = Pattern.compile("[- ]?[0-9]*\\.?[0-9] ([eE][- ]?[0-9] )?");

public static double[] extractDoubles(String input) {
    return DOUBLE_PATTERN.matcher(input).results()
        .mapToDouble(m -> Double.parseDouble(m.group()))
        .toArray();
}

public static void main(String[] args) {
    String input = "!Triangle(1.1,1.2,1.3)";
    System.out.println(Arrays.toString(extractDoubles(input)));
}

output:

[1.1, 1.2, 1.3]

CodePudding user response:

If I understand your problem correctly, your input string is like the following:

!Circle(1.234)

or even

{!Rectangle(1.2,1.3)}

You could "gather" all the numbers in your input string. For that you'd typically need a regular expression.

But I guess you're trying to write something that acts like an interpreter or something. In that case you'd need to write a state machine, that interprets (character for character) the whole input. That a way more complex thing to do.

  •  Tags:  
  • java
  • Related