Since Java doesn't have an eval()
module, and I want to write my own regex to parse strings into a double[][]
, e.g.
[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? I.e.:
Now, the code is sort of cheating by know that my inner size of the double[][] is 2 and during iteration through
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?Currently it's reading into the
d1
andd2
variable before create a newdouble[]
to add to theList
, is there a way to do it directly without creatingd1
andd2
?