views:

51

answers:

3

I have a String in this form:

String buf = "[[[name11,name12]][[name21,name22]][[name31,name32]]]";

How can I retrieve all the names?

When i retreive data from database i recive it in this form.

Looking for Java Solution.

Thanks

+1  A: 

You can use the Scanner class in Java to parse the data.

Faisal Feroz
+2  A: 

This trick should do it:

String csv = buf.replace("[[[","").replace("]]]","").replace("]][[",",");
String[] names = csv.split(",");

It removes the leading and trailing brackets and replaces the inner brackets with a comma. Now you can split the input around , and have an array with the names only.

Andreas_D
String csv = buf.replace("[","").replace("]","") // simpler?
Tom Anderson
String[] names = buf.split("[,[\\]]+"); // even simpler but not sure about the escaping?
Tom Anderson
@Tom, no, `buf.replace("[","").replace("]","")` won't work: it "glues" `name12` and `name21` together (and the other names as well).
Bart Kiers
@Bart: true; // should have thought of that, sorry
Tom Anderson
A: 

Do you always have pairs of names? Is it possible to have [[name2,]]?

If the names always come in pairs then Andreas_D response is a simple straight forward answer. If one of the names may be missing then you need to add a couple of replace() calls in front to look for these and put dummy values in. Specifically "[," with "[dummyFirst," and ",]" with ",dummyLast]". You would then have to process these dummy values according to whatever rules are appropriate for your context.

BigMac66