如何拆分和替换逗号和括号?

时间:2017-12-19 07:00:42

标签: java android regex

我有字符串值

String valueData = "{\"x\":10,\"y\":10,\"z\":10}"

如何格式化为x:10,y:10,z:10

请帮我正则表达

4 个答案:

答案 0 :(得分:5)

String valueData = "{\"x\":10,\"y\":10,\"z\":10}.";
valueData = valueData.replace(".", "");
valueData = valueData.replace("{", "");
valueData = valueData.replace("}", "");
valueData = valueData.replace("\"", "");
System.out.println(valueData);

答案 1 :(得分:1)

String valueData = {"x":10,"y":10,"z":10}.它无效String我认为它是JSON

你也可以尝试这个

  StringBuilder stringBuilder= new StringBuilder();
    try {
        JSONObject json = new JSONObject("{\"x\":10,\"y\":10,\"z\":10}");
        Iterator<String> iter = json.keys();
        while (iter.hasNext()) {

            String key = iter.next();
            stringBuilder.append(key+ ":");
            stringBuilder.append(json.getString(key)+",");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.e("DATA",stringBuilder.toString());

<强>输出

com.example.user33.workingtestapp E/DATA: x:10,y:10,z:10,

答案 2 :(得分:1)

你可以用这个:

String valueData = "{\"x\":10,\"y\":10,\"z\":10}";
String s = valueData
                .substring(1, valueData.length() - 1)
                .replaceAll("(\\\")(\\w+)(\\\")", "$2");

答案 3 :(得分:1)

您可以使用:

    valueData = valueData.replaceAll("[{\"}\\.]+", "");
    System.out.println(valueData);//x:10,y:10,z:10