I am thinking String.split()
. We first want to split the part of the message inside the curly braces at commas, then at equal signs. However, not at every comma, obviously. Only at commas that go right before a new key letter and an equal sign. In code:
String message
= "Value{A=10,B=20,C=30,"D=700-2-1, Bourke STREET, SOUTH 2/28 QUEEN ST,E=40,F=50}";
String contents = message.replaceFirst("^Value\\{(.*)\\}$", "$1");
String[] pairs = contents.split(",(?=[ABCDEF]=)");
Map<String, String> m = Arrays.stream(pairs)
.map(p -> p.split("=", 2))
.collect(Collectors.toMap(a -> a[0], a -> a[1]));
m.forEach((k, v) -> System.out.println(k + " -> " + v));
Output is:
A -> 10
B -> 20
C -> 30
D -> 700-2-1, Bourke STREET, SOUTH 2/28 QUEEN ST
E -> 40
F -> 50
(?=[ABCDEF]=)
in the second regular expression is a positive lookahead. It makes sure that we only match the comma if it is followed by one of those letters and en equal sign. If letters can be other than ABCDEF, you may want to use \w
for a word character instead of [ABCDEF]
.
We don’t necessarily need a stream operation, but you had tagged your question java-stream, so I thought you would like to see one.
The stream operation is not guaranteed to give you a HashMap
. Even if you observe that it does (which it did on Java 11 in my case), it may not on the next Java version or even with different input. For the majority of cases this should be no concern. If you have a specific reason for needing to be sure, check what you got and convert if it wasn’t a HashMap
:
if (! m.getClass().equals(HashMap.class)) {
m = new HashMap<>(m);
}