Labels { public static Labels fromString(String string) throws IllegalArgumentException { if (string == null || string.equals("")) { return new Labels(Collections.emptyMap()); } Matcher m = COMMA_SPLITTER.matcher(string); int lastEnd = 0; while (m.find()) { String pair = string.substring(lastEnd, m.start()); if (pair.isEmpty()) { throw new IllegalArgumentException(); } lastEnd = m.end(); } String lastPair = string.substring(lastEnd); if (lastPair.isEmpty()) { throw new IllegalArgumentException(); } String[] pairs = COMMA_SPLITTER.split(string.trim()); Map<String, String> map = new HashMap<>(pairs.length); for (String pair : pairs) { String[] keyValue = EQUAL_SPLITTER.split(pair, 2); if (keyValue.length < 2) { throw new IllegalArgumentException("Couldn't parse the label=value pair: " + pair); } map.put(keyValue[0], keyValue[1]); } checkLabels(map); return new Labels(map); } Labels(String... labels); private  Labels(Map<String, String> labels); static Labels fromString(String string); Map<String, String> labels(); @Override String toString();  }
@Test public void testParser() { assertParseThrows("foo"); assertParseThrows("foo=bar,"); assertParseThrows("foo==bar"); assertParseThrows("foo!=bar"); assertParseThrows("foo=bar,"); assertParseThrows("foo=bar,,"); assertParseThrows(",foo=bar"); assertParseThrows(",,foo=bar"); assertParseThrows("8/foo=bar"); assertParseThrows(" assertParseThrows("a/b/foo=bar"); assertParseThrows("foo=bar/"); assertDoesNotThrow(() -> { Labels.fromString("foo="); Labels.fromString("foo=bar"); Labels.fromString("foo/bar=baz"); Labels.fromString("foo.io/bar=baz"); Labels.fromString("foo=bar,name=gee"); Labels.fromString("foo=bar,name="); Labels.fromString("foo=bar,lala/name="); }); }