简体   繁体   English

将字符串转换为double [] []-Java

[英]Converting a string into a double[][] - Java

Since Java doesn't have an eval() module , and I want to write my own regex to parse strings into a double[][] , eg 由于Java 没有eval()模块 ,因此我想编写自己的正则表达式将字符串解析为double[][] ,例如

[in]: [在]:

`{{1.23,8.4},{92.12,-0.57212}}`
`{{1.23,-8.4}, {-92.12,-0.57212}}`

[code]: [码]:

 double[][] xArr;
 // Somehow read the string into something like this:
 xArr = new double[][] {{1.23,8.4},{92.12,-0.57212}};
 System.out.println(xArr[0][0] + " " + xArr[0][1]);

[out]: [出]:

 1.23 -8.4

Currently, I'm doing it as such: 目前,我正在这样做:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import java.util.ArrayList;
import java.util.List;

public class HelloWorld {

    public static void main(String[] args) {
        String s = "{{1.23,8.4}, {92.12,-0.57212}}";

        Pattern regex = Pattern.compile("((-)?\\d+(?:\\.\\d+)?)");
        Matcher matcher = regex.matcher(s);
        List<double[]> locations = new ArrayList<double[]>();
        int i = 0;
        while(matcher.find()){
            double d1 = Double.parseDouble(matcher.group(1));
            matcher.find();
            double d2 = Double.parseDouble(matcher.group(1));
            locations.add(new double[] {d1, d2});
            i++;        
        }; 


    }

}

Is there a better way to do this? 有一个更好的方法吗? Ie: 即:

  • Now, the code is sort of cheating by know that my inner size of the double[][] is 2 and during iteration through match.find() . 现在,代码知道我的double [] []的内部大小是2,并且在迭代过程中通过match.find() It does 2 passes to skip to the next pair, is there a way to change the regex such that it extracts 2 groups at a time? 它执行2次传递以跳到下一个对, 是否有办法更改正则表达式以使其一次提取2组?

  • Currently it's reading into the d1 and d2 variable before create a new double[] to add to the List , is there a way to do it directly without creating d1 and d2 ? 目前,它正在读取d1d2变量,然后创建一个新的double[]以添加到List有没有一种方法可以直接执行而不创建d1d2

Use jackson but you will have to replace the braces with boxes/parenthesis. 使用杰克逊,但您必须将方括号替换为方格/括号。

With this you don't need to specify the dimensions of the expected array 这样,您无需指定期望数组的尺寸

public static void main(String[] args) throws IOException {
    String jsonString = "{{1.23,8.4}, {92.12,-0.57212}}";
    jsonString = jsonString.replace("{", "[").replace("}", "]");
    Double[][] doubles = new ObjectMapper().readValue(jsonString, Double[][].class);
    System.out.println(Arrays.deepToString(doubles));
}

Here is a Java 8 solution I came up with: 这是我想出的Java 8解决方案:

String test = "{{1.23,8.4},{92.12,-0.57212}}";

double[][] vals = Arrays.stream(test.replaceAll(" ", "").split("},\\{"))
                        .map(str -> str.replaceAll("[{}]", "").split(","))
                        .map(Arrays::stream)
                        .map(stream -> stream.mapToDouble(Double::parseDouble)
                                             .toArray())
                        .toArray(double[][]::new);

System.out.println(Arrays.deepToString(vals));

Output: 输出:

[[1.23, 8.4], [92.12, -0.57212]]

Or if you want a Double[][] : 或者,如果您想要Double[][]

Double[][] vals = Arrays.stream(test.replaceAll(" ", "").split("},\\{"))
                        .map(str -> str.replaceAll("[{}]", "").split(","))
                        .map(Arrays::stream)
                        .map(stream -> stream.map(Double::parseDouble)
                                             .toArray(Double[]::new))
                        .toArray(Double[][]::new);

Explanation: 说明:

First any whitespace is removed and the string is split on the pattern },\\\\{ which will result in a String[] where each String is one of the double[] s with some excess curly braces: 首先,删除所有空格,并在模式},\\\\{上拆分字符串},\\\\{这将导致String[] ,其中每个String都是double[]之一,带有一些多余的花括号:

["{{1.23,8.4", "92.12,-0.57212}}"]

Then, for each String the curly braces are removed, and the String is split again. 然后,为每个String除去花括号,然后再次拆分String So each String becomes a String[] where each value is the String representation of a " double ": 因此,每个String将成为String[] ,其中每个值都是“ double ”的String表示形式:

[["1.23", "8.4"],["92.12", "-0.57212"]]

These strings are then parsed into doubles, and everything is collected into a double[] and then a double[][] : 然后将这些字符串解析为double,并将所有内容收集到double[]double[][]

[[1.23, 8.4], [92.12, -0.57212]]
  1. Question: 题:

    is there a way to change the regex such that it extracts 2 groups at a time 有没有办法更改正则表达式,使其一次提取2组

Yes. 是。 You could extract a whole line with one pattern, by using your existing one. 您可以使用现有的一种模式提取整行。 You have to add the paranthesis and the komma and a the + operator (for multiple values). 您必须添加paranthesis和komma以及+运算符(用于多个值)。 When you have a single line, you can extract the values with your current pattern, until there are no more found (with a while loop). 如果只有一行,则可以使用当前模式提取值,直到不再找到为止(带有while循环)。

  1. Question: 题:

    is there a way to do it directly without creating d1 and d2? 有没有一种方法可以直接执行而不创建d1和d2?

I don't know exactly what you mean. 我不知道你到底是什么意思 Where is the problem with creating them? 创建它们的地方在哪里? With the suggested way on question 1, you could store every value directly in a list as well and hen create a array from it. 使用关于问题1的建议方法,您也可以将每个值也直接存储在列表中,然后从中创建一个数组。

I like the solution of Olayinka, too if your format dont change. 如果您的格式不变,我也喜欢Olayinka的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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