简体   繁体   中英

How can I extract and separate double values from String?

Let's say that I receive a java String message = "a=5.31,b=2.004,c=3.1230" that sends 3 variables I want in a single String message.

How can I extract the accurate value of a,b,c and then have 3 double OR string variables x,y,z hold the values of a,b,c respectively? Preferably, I'd like this to be able to handle any number of decimal places (or at the very least up to 4 dp).

I've read the thread on using regex to extract numbers from String messages, but I could not find a way to separate the resulting numbers after passing it through the matcher.

Is there a library I could import for this?

I am currently using Android Studio supporting API 21 and above for this problem.

A fragile, draft solution could involve a pattern/matcher combination with iteration and back-references, as well as the parsing utility method from Double .

Something like:

String test = "a=5.31,b=2.004,c=3.1230";
//                          | [letter(s)]=
//                          |    | group 1: digits and dots
//                          |    | 
Pattern p = Pattern.compile("\\w+=([\\d.]+)");
Matcher m = p.matcher(test);
// iterating on findings
while (m.find()) {
    // back-reference
    String match = m.group(1);
    // trying to parse combination of digits and dots as double
    try {
        double d = Double.valueOf(match);
        System.out.printf("Found double: %f%n", d);
    }
    // handling non-parseable combinations of digits and dots
    catch (NumberFormatException nfe) {
        // TODO handle
        System.out.printf("Couldn't parse %s as double.%n", match);
    }
}

Output

Found double: 5.310000
Found double: 2.004000
Found double: 3.123000

Note

The output pads additional 0 s because of the default printf representation.

Use String.split :

String message = "a=5.31,b=2.004,c=3.1230";
String[] kvpairs = message.split(",");
Double x = Double.valueOf(kvpairs[0].split("=")[1]);
Double y = Double.valueOf(kvpairs[1].split("=")[1]);
Double z = Double.valueOf(kvpairs[2].split("=")[1]);
System.out.println(z);

prints "3.123"

使用String的split方法:

Arrays.asList(line.trim().split(",")).stream.map(w -> w.split("=")[1].trim())...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM