0

I am reading from a file, and copying the double values within it into an array.

String regEx = "\\s(\\d,??\\d??)";
line = scanner.nextLine();
pattern = Pattern.compile(regEx);
matcher = pattern.matcher(line);
if(matcher.find()) {
    System.out.println(matcher.group(1));
    grades[i++] = Double.parseDouble(matcher.group(1));
}

But this only seems to copy the whole number part from the file, not the part after the ".", the fraction. It appears to completely ignore the part of the regex that is quantified by "??". I assume it is a problem with my regex, I cannot figure out what is wrong tho-

Crenshaw
  • 13
  • 5
  • What does the contents of your file look like? – Jacob G. Feb 22 '19 at 20:09
  • an excerpt would be: 2263441 3 2269087 2,7 2273204 3,7 2273794 4 2277979 3 2281178 2,3 – Crenshaw Feb 22 '19 at 20:11
  • I changed the commas to dots previously in my loop that goes over the file. I just skipped that part after line 2 in my code above, line gets modified – Crenshaw Feb 22 '19 at 20:13
  • Try `"(?<!\\S)\\d+(?:,\\d+)?"`. If you have a dot, replace `,` with `\\.`. Also, use `matcher.group()` with this regex. – Wiktor Stribiżew Feb 22 '19 at 20:13
  • @WiktorStribiżew that doesnt work unfortunately. I commented above the structure of the file. This regex takes the big whole number, but I only care about the small decimal number. That is why \\s is included in my regex – Crenshaw Feb 22 '19 at 20:19
  • So, you mean by "doesnt work" that you do not get the fraction only? Try `"\\s\\d+(?:,(\\d+))?)"` then. Here, in Group 1, there will be only `7` from `3,7`. – Wiktor Stribiżew Feb 22 '19 at 20:21
  • No I am sorry, you misunderstood. Every line looks like this 2269087 3 or 2273204 3,7 for example so it has a big number followed by a smaller number in every line. I want the 2nd number, the small number. But my regex only returns the small number floored. Your regex gives me the big number, 2269087 for example. I am sorry I don't know how to put it more precisely. – Crenshaw Feb 22 '19 at 20:25
  • Try `"\\d\\s+(\\d+(?:,\\d+)?)"`, see https://regex101.com/r/qJHeon/2. – Wiktor Stribiżew Feb 22 '19 at 20:38
  • So, the problem is that you made two consecutive patterns optional, while you should have made their *sequence* optional. It is a very common issue. – Wiktor Stribiżew Feb 22 '19 at 20:43
  • If you don't mind explaining further, why didn't mine originally work? Since there can't be a number like 2. or 4. with no fraction after the comma, I would assume it does not matter if I check for ".x" or "." and "x". – Crenshaw Feb 22 '19 at 20:48

1 Answers1

0

Okay the regular expression I was looking for is "\\s(\\d(\\.\\d)?)"

Crenshaw
  • 13
  • 5