tags:

views:

85

answers:

2

I have a String like this.

{"type":"broad","Text":"cat"},{"type":"broad","Text":"dog"}

String[] keyString = getParts({"type":"broad","Text":"cat"},{"type":"broad","Text":"dog"});
for(String part : keyString){
    some code here which gives like this 
    String text = "cat";
    String type = "broad";
}

Can some one tell me how can i get text and type separately in a string

public static String[] getParts(String keyString) {
  if(keyString.isEmpty()) 
   return null;
  String[] parts  = keyString.split(",");
  return parts;
 }

Or is there any easy ways to get the respective strings.

+3  A: 

This looks like JSON, so if you have / create a class with fields type and Text, you can use gson or Jackson to parse the string and obtain objects of that class. (You can still split the string with split(",") and parse each part as separate JSON string)

Bozho
One problem though, the array doesn't start nor ends with `[`, `]` respectively.
The Elite Gentleman
@Bozho, you are right it is JSON string. Initially i had JSONstring like this JSONString = [{"type":"broad","Text":"cat"},{"type":"broad","Text":"dog"}] After doing the following JSONArray arrayKey = new JSONArray(JSONString); arraykey = {"type":"broad","Text":"cat"},{"type":"broad","Text":"dog"}
salman
@salman: Then use a JSON parser, the right tool for the job.
Christoffer Hammarström
+2  A: 

This should do the trick:

import java.util.regex.*;

public class Test {

    public static void main(String[] args) {

        String input = "{\"type\":\"broad\",\"Text\":\"cat\"}," +
                       "{\"type\":\"broad\",\"Text\":\"dog\"}";

        System.out.println(input);

        Pattern partPattern = Pattern.compile("\\{([^}]*)\\}");
        Pattern typePattern = Pattern.compile("\"type\":\"([^\"]*)\"");
        Pattern textPattern = Pattern.compile("\"Text\":\"([^\"]*)\"");

        Matcher m = partPattern.matcher(input);
        while (m.find()) {
            Matcher typeMatcher = typePattern.matcher(m.group(1));
            Matcher textMatcher = textPattern.matcher(m.group(1));

            String type = typeMatcher.find() ? typeMatcher.group(1) : "n/a";
            String text = textMatcher.find() ? textMatcher.group(1) : "n/a";

            System.out.println(type + ", " + text);
        }
    }
}

Output (ideone link):

{"type":"broad","Text":"cat"},{"type":"broad","Text":"dog"}
broad, cat
broad, dog
aioobe
+1 for using RegExp
The Elite Gentleman