Home > Blockchain >  how to read key and value within string containing square brackets using java
how to read key and value within string containing square brackets using java

Time:11-24

Have got followings string reading the docker logs Example: xmen logging; xmenID=642c7ded-2fef-4aa3-ba08-0b6ab7f7a5e0; period=[name:search, actions:[start:0 ms, material requests:0 ms, fulfilled requests:329 ms, sum responses:1 ms, total:330 ms]] And using the regex and have got following string [start:0 ms, material requests:0 ms, fulfilled requests:329 ms, sum responses:1 ms, total:330 ms]

How to fetch the values of starts, material requests to check their values are equal to zero or more using java?

CodePudding user response:

Given that you've already parsed out the values into a String, you can simply split and collect them into a Map<String, String>.

String valueOutOfRegex = "[start:0 ms, material requests:0 ms, fulfilled requests:329 ms, sum responses:1 ms, total:330 ms]"; // Your String that you've parsed
String valueWithRemovedBrackets = valueOutOfRegex.substring(1, valueOutOfRegex.length() - 1); // remove the leading and trailing brackets
Map<String, String> simpleMap = Arrays.stream(valueWithRemovedBrackets.split(",")).collect(Collectors.toMap(s1 -> s1.split(":")[0].trim(), s1 -> s1.split(":")[1]));  // collect into a Map

This will give you a Map<String, String> that looks like this:

{total=330 ms, fulfilled requests=329 ms, material requests=0 ms, start=0 ms, sum responses=1 ms}
  • Related