My input is a string with annotations and data:
var string = "@anno1[ data1 xyz @anno2[data2 @anno3[data3] data4] data5 @anno4[data6] data7]"
I want to transform this string into an object with structured information:
var childs = [
{
name : '@anno1',
text : 'data1 xyz data2 data3 data4 data5 data6 data7',
},
{
name : '@anno2',
text : 'data2 data3 data4'
},
{
name : '@anno3',
text : 'data3'
},
{
name : '@anno4',
text : 'data6'
}
]
I have attempted various methods but so far, none have been successful. Any help would be greatly appreciated.
Below is the Java code I have tried utilizing:
import java.util.HashMap;
import java.util.Map;
public class ExpressionTree {
static Map <String, String> resultMap = new HashMap<String, String>(16);
public static void main(String args[]) {
// String exp = "[data1 xyz @anno2[data2 @anno3[data3] data4] data5 @anno4[data6] data7]";
String exp = "@anno1[ data1 xyz @anno2[data2 @anno3[data3] data4] data5 @anno4[data6] data7 ]";
parseRecursively(exp);
}
private static void parseRecursively(String exp) {
String annotation = null;
String annotationValue = null;
if (exp.startsWith("@")) {
int dataStartIndex = exp.indexOf("[");
annotation = exp.substring(0, dataStartIndex);
annotationValue = exp.substring(0 + dataStartIndex, exp.lastIndexOf("]")+1).trim();
System.out.println(annotation);
System.out.println(annotationValue);
resultMap.put(annotation, annotationValue);
parseRecursively(annotationValue);
} else {
int annotationStartIndex = exp.indexOf("@");
int dataStartIndex = exp.substring(1).indexOf("[");
if( -1 != annotationStartIndex || -1 != dataStartIndex)
{
annotation = exp.substring(annotationStartIndex, dataStartIndex+1).trim();
String nextData = exp.substring(0 + dataStartIndex + 1).trim();
String tmpNextData = nextData;
int countOfOpenBrackets = 0;
for (int i = 0; tmpNextData.charAt(i) != ']'; i++) {
// System.out.println(tmpNextData.charAt(i));
if (tmpNextData.charAt(i) == '[') {
countOfOpenBrackets++;
}
// tmpNextData = tmpNextData.substring(1);
}
tmpNextData = nextData;
int endIndexOfCurrentData = 0;
for (int i = 0; i < tmpNextData.length() && endIndexOfCurrentData == 0; i++) {
// System.out.println(tmpNextData.charAt(i));
if (tmpNextData.charAt(i) == ']') {
countOfOpenBrackets--;
}
if (countOfOpenBrackets == 0) {
endIndexOfCurrentData = i + 1;
}
// tmpNextData = tmpNextData.substring(1);
}
annotationValue = nextData.substring(0, endIndexOfCurrentData).trim();
System.out.println(annotation);
System.out.println(annotationValue);
resultMap.put(annotation, annotationValue);
parseRecursively(annotationValue);
}
}
System.out.println(resultMap);
}
}