0

How to extract double values from a string?

For example, s= "1.2+3.4*(3.2+2.3)-12.1/3.4*1.8+5.7"

How do extract the double values, and store it as variables?

jmj
  • 237,923
  • 42
  • 401
  • 438
Sophie
  • 69
  • 1
  • 9
  • 2
    do pattern matching and grab the matching portion – jmj Mar 21 '14 at 23:19
  • How do I do pattern matching?Thanks! – Sophie Mar 21 '14 at 23:21
  • 1
    Take a look [here](https://stackoverflow.com/questions/1432245/java-parse-a-mathematical-expression-given-as-a-string-and-return-a-number), it has been answered already. – berbt Mar 21 '14 at 23:23
  • first convert it into char array, then search for all the operations, +,-,* and /. You can push them into stack and then take the chars till next operator. – Aditya Peshave Mar 21 '14 at 23:23
  • Have you tried this [link](http://stackoverflow.com/questions/5769669/java-convert-string-to-double)? I think it's what you need – Guy Krief Mar 21 '14 at 23:23
  • I would suggest searching for regular expression examples in the code base you use, I think your getting a "pass" for being female. normally such a question which is not researched would get you boiled in oil. – alexmac Mar 22 '14 at 02:47

1 Answers1

2

You can do it with Pattern matching and grab matching portion out

Pattern p = Pattern.compile("[0-9]*\\.?[0-9]+");
Matcher m = p.matcher("1.2+3.4*(3.2+2.3)-12.1/3.4*1.8+5.7");

while (m.find()) {
  System.out.println(m.group());
}

You can then collect all matched data to a List<Double> or List<Float> based on your requirement

To collect operators as well you need to add another pattern to look for as well see the ORing section

([0-9]*\.?[0-9]+)|(\+|-|\/|\(|\|\)|\*)

See

jmj
  • 237,923
  • 42
  • 401
  • 438
  • what kind of head do I need to import for Pattern and Matcher? – Sophie Mar 21 '14 at 23:36
  • `java.util.regex.Pattern` & `java.util.regex.Matcher` – jmj Mar 21 '14 at 23:37
  • The Netbeans shows red line under the Pattern and Matcher, and it says cannot find class Pattern and Matcher, so my question is if I need to import something? – Sophie Mar 21 '14 at 23:40
  • As mentioned you need to import these two classes – jmj Mar 21 '14 at 23:41
  • My last question is how do I store each characters as a varible. I mean numbers and +,-,/ all those signs in a varible? – Sophie Mar 21 '14 at 23:50
  • You can store each matched data into a List as mentioned in answer, if you want to grab operators (`-`, `+`, etc..) you will have to change the pattern so that it grabs them as well – jmj Mar 21 '14 at 23:51
  • how do I grab the +-/*, could you show me the code? – Sophie Mar 21 '14 at 23:58
  • how do I do the pattern match for"+,-,*,/"? – Sophie Mar 22 '14 at 00:30