I have tried alterations using '|' but seems to be impossible to first parse map if possible, if not, just parse the value as a whole, but keeping the capture group as no 1/2, tried with branch reset group but didn't manage that way either. Any suggestions are welcome.
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Scratch {
public static void main(String[] args) {
final Pattern outerKeyPattern = Pattern.compile("([A-Z]+)\\((.*)\\)", Pattern.MULTILINE);
final Pattern innerPattern = Pattern.compile("([A-Z]+)\\((.*?)\\)");
// There will always be a value in the outer,
// but sometimes it's an inner map, i.e only need to solve this case, no other exeptions
String input = """
VALUE(123)
OUTERVALUE(INNERVALUE(123)OTHERVALUE(456))
""";
Map<String, Map<String, String>> outer = new HashMap<>();
Matcher matcher = outerKeyPattern.matcher(input);
while (matcher.find()) {
String key = matcher.group(1);
String value = matcher.group(2);
Matcher valueMatcher = innerPattern.matcher(value);
Map<String, String> innerMap = new HashMap<>();
while (valueMatcher.find()) {
innerMap.put(valueMatcher.group(1), valueMatcher.group(2));
}
outer.put(key, innerMap);
}
System.out.println(outer);
}
}
yields output:
{VALUE={}, OUTERVALUE={INNERVALUE=123, OTHERVALUE=456}}
I need to parse value also as key for the inner map and it's value as null:
{VALUE={123=}, OUTERVALUE={INNERVALUE=123, OTHERVALUE=456}}