I have the following content in a file that I need to parse.
((-2, -1 ), ( 4, 2) ) ((-1.2, 0), (0, 0))
((0, 0), (10, -1))
((5, 3), (5, 4)) ((5, 1) , (5, 5))
((8, 3), (10, 3))
((8, 5), (11.5, 5))
So far, I have scanned through the file and taken the input line by line, saving them as strings, so one string would be ((-2, -1 ), ( 4, 2) ) ((-1.2, 0), (0, 0)). My question is where to go from here. How do I extract the doubles from this String. I have tried to use the parentheses as a delimiter, as well as changing all of the parentheses to commas, and then using a comma as a delimiter, but both of these ways give me errors. Any ideas?
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1 at java.util.regex.Pattern.error(Unknown Source) at
java.util.regex.Pattern.accept(Unknown Source) at
java.util.regex.Pattern.group0(Unknown Source) at
java.util.regex.Pattern.sequence(Unknown Source) at
java.util.regex.Pattern.expr(Unknown Source) at
java.util.regex.Pattern.compile(Unknown Source) at
java.util.regex.Pattern.<init>(Unknown Source) at
java.util.regex.Pattern.compile(Unknown Source) at
java.lang.String.replaceAll(Unknown Source)
The whole purpose of this is to create points from these doubles. For example, ((0, 0), (10, -1)) would create two points, (0,0) and (10, -1). I have created the point class and it takes in two doubles in the constructor.
Here is what I tried:
String toParse = "((0, 0), (10, -1))";
toParse.replaceAll("(", ",");
toParse.replaceAll(")", ",");
Scanner stringScanner = new Scanner(toParse);
stringScanner.useDelimiter(",");
while(stringScanner.hasNextDouble()){
ect
The error message you get is because
(and)are special regex characters: so whenever you want to replace (or match) them, you need to escape them with a backslash:That said, you might want to use a Pattern/Matcher approach here:
which produces:
What the code does: it searches for the pattern
-?\d+(\.\d+)?and parses each string that matches said pattern to adouble. The pattern itself means: