开发者

String of arrays parsing

开发者 https://www.devze.com 2023-01-19 19:55 出处:网络
I have a String like this. {\"type\":\"broad\",\"Text\":\"cat\"},{\"type\":\"broad\",\"Text\":\"dog\"}

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";
    Str开发者_如何转开发ing 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.


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)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消