2

I have a String to represent an entity and its properties(also an entity) like : String input = "apple{shape,color},orange{taste,price}";

I want it to split to an array :

array[0] = apple{shape,color};
array[1] = orange{taste,price};

any words even it has no {xxx} can be considered as a entity so do shape and color.

So if I have a String input = "shape,color"

array[0] = shape
array[1] = color

The depth may be more:String input = "Fruit{apple{shape,color},orange{taste,price}}";

array[0] =  Fruit{apple{shape,color},orange{taste,price}}

I tried this but it does not work well,

public static String[] split(String input){
    String[] groups = input.split("(?<=\\}),(?=\\w+\\{)");
    return groups;
}
JaskeyLam
  • 15,405
  • 21
  • 114
  • 149
  • 1
    What is the expected output for `Fruit{apple{shape,color},orange{taste,price}}` – vks Aug 19 '15 at 05:58
  • @vks, the same string returns since it it a whole entity – JaskeyLam Aug 19 '15 at 06:01
  • 1
    possible duplicate of [Can regular expressions be used to match nested patterns?](http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns) – Andreas Aug 19 '15 at 06:02
  • I remember writing a regex solution based on .NET that supports balanced constructs. I do not think you can achieve your goal that easily in Java. You need to create a method parsing the strings the way you need. – Wiktor Stribiżew Aug 19 '15 at 06:12

1 Answers1

0

You can use stack to check balance of expression and then assign it as array element. I'll write a pseudo code for you:

string s = ""; //initial assignment
stack t;
for i from 0 to exp.length     //exp is your input expression
    if(exp[i] == ',' && stack is empty && s is not null)
        a[k++]=s;
        s = "";
        continue;
    s+=exp[i];
    if(exp[i] == '{')        //I'm checking balance for '{' only, you can extend it further as required
        t.push('{');
    if(exp[i] == '}')
        t.pop();
vish4071
  • 5,135
  • 4
  • 35
  • 65