VolumeAnnotator implements SugiliteTextAnnotator { @Override public List<AnnotatingResult> annotate(String text) { text = text.replaceAll("[\\u00A0\\u2007\\u202F]+", " "); if (cache.containsKey(text)){ return cache.get(text); } List<AnnotatingResult> results = new ArrayList<>(); String regex = "\\b\\d+?(.\\d+?)?(\\s)?(m[Ll]?|L|(fl )?oz|ounce(s)?|tsp|cp|pt|qt|gal)\\b"; Pattern pattern = Pattern.compile(regex); int curEnd = -3; Matcher matcher = pattern.matcher(text); while (matcher.find()) { String matchedString = text.substring(matcher.start(), matcher.end()); String[] parsed; if (matchedString.contains(" ")) parsed = matchedString.split(" "); else { parsed = new String[2]; parsed[0] = matchedString.split("[a-z]")[0]; parsed[1] = matchedString.substring(parsed[0].length()); } double num = Double.valueOf(parsed[0]); if (parsed[1].startsWith("m")) num *= MILLILITER; else if (parsed[1].startsWith("L")) num *= LITER; else if (parsed[1].startsWith("f")) num *= OUNCE; else if (parsed[1].startsWith("o")) num *= OUNCE; else if (parsed[1].startsWith("t")) num *= TABLESPOON; else if (parsed[1].startsWith("c")) num *= CUP; else if (parsed[1].startsWith("p")) num *= PINT; else if (parsed[1].startsWith("q")) num *= QUART; else if (parsed[1].startsWith("g")) num *= GALLON; if (matcher.start() - curEnd == 1 && text.charAt(curEnd) == ' ') { AnnotatingResult last = results.get(results.size() - 1); last.setNumericValue(last.getNumericValue() + num); } else { AnnotatingResult res = new AnnotatingResult(RELATION, text.substring(matcher.start(), matcher.end()), matcher.start(), matcher.end(), num); results.add(res); } curEnd = matcher.end(); } cache.put(text, results); return results; } VolumeAnnotator(); @Override List<AnnotatingResult> annotate(String text); static void main(String[] args);  }
@Test public void testMultiple() { List<SugiliteTextParentAnnotator.AnnotatingResult> res = annotator.annotate("Small: 100 mL, Medium: 4 fl oz, " + "Large: 5.55 ounce, ExLarge: 1 cp 3 oz, SuperLarge: 1.2 pt, Enormous: 3 gal 4 qt"); assertEquals(res.size(), 6); assertEquals(res.get(0).getRelation(), SugiliteRelation.CONTAINS_VOLUME); res.sort(Comparator.comparingDouble(SugiliteTextParentAnnotator.AnnotatingResult::getNumericValue)); assertEquals(res.get(0).getNumericValue().intValue(), (int)(100*MILLILITER)); assertEquals(res.get(1).getNumericValue().intValue(), (int)(4*OUNCE)); assertEquals(res.get(2).getNumericValue().intValue(), (int)(5.55*OUNCE)); assertEquals(res.get(3).getNumericValue().intValue(), (int)(CUP+3*OUNCE)); assertEquals(res.get(4).getNumericValue().intValue(), (int)(1.2*PINT)); assertEquals(res.get(5).getNumericValue().intValue(), (int)(3*GALLON+4*QUART)); }