PercentageAnnotator 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)?(%|percent)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); while (matcher.find()) { try { String matchedString = text.substring(matcher.start(), matcher.end()); if (matcher.start() > 0 && text.charAt(matcher.start() - 1) == '-') matchedString = text.substring(matcher.start() - 1, matcher.end()); String[] parsed = matchedString.split("[p %]"); results.add(new AnnotatingResult(RELATION, text.substring(matcher.start(), matcher.end()), matcher.start(), matcher.end(), Double.valueOf(parsed[0]))); } catch (Exception e) { e.printStackTrace(); } } cache.put(text, results); return results; } PercentageAnnotator(); @Override List<AnnotatingResult> annotate(String text);  }
@Test public void testMultiple() { List<SugiliteTextParentAnnotator.AnnotatingResult> res = annotator.annotate("35 percent of the class" + "get an A while 25.95% get a B"); assertEquals(res.size(), 2); assertEquals(res.get(0).getRelation(), SugiliteRelation.CONTAINS_PERCENTAGE); assertEquals(res.get(1).getRelation(), SugiliteRelation.CONTAINS_PERCENTAGE); res.sort(Comparator.comparingDouble(SugiliteTextParentAnnotator.AnnotatingResult::getNumericValue)); assertEquals(res.get(0).getNumericValue().intValue(), 25); assertEquals(res.get(1).getNumericValue().intValue(), 35); }
@Test public void testMultipleWithBadInput() { List<SugiliteTextParentAnnotator.AnnotatingResult> res = annotator.annotate("stock market growth rate:" + "-550.1 %, 4, 3.% and 0.0006 percent"); assertEquals(res.size(), 2); res.sort(Comparator.comparingDouble(SugiliteTextParentAnnotator.AnnotatingResult::getNumericValue)); assertEquals(res.get(0).getNumericValue().intValue(), -550); assertEquals(res.get(1).getNumericValue().intValue(), 0); }