-2

我需要解析下面给出的 JSON 代码类型的几行。我需要删除方括号内的所有逗号(,)。那就是["Cheesesteaks","Sandwiches", "Restaurants"]变成["Cheesestakes""Sandwiches""Restaurants"]。我需要保留所有其他逗号。

另一个例子 -["Massachusetts Institute of Technology", "Harvard University"]["Massachusetts Institute of Technology""Harvard University"]保持所有其他逗号不变。

{"business_id": "EjgQxDOUS-GFLsNxoEFJJg", "full_address": "Liberty Place\n1625 Chestnut St\nMantua\nPhiladelphia, PA 19103", "schools": ["Massachusetts Institute of Technology", "Harvard University"], "open": true, "categories": ["Cheesesteaks", "Sandwiches", "Restaurants"], "photo_url": "http://s3-media4.ak.yelpcdn.com/bphoto/SxGxfJGy9pXRgCNHTRDeBA/ms.jpg", "city": "Philadelphia", "review_count": 43, "name": "Rick's Steaks", "neighborhoods": ["Mantua"], "url": "http://www.yelp.com/biz/ricks-steaks-philadelphia", "longitude": -75.199929999999995, "state": "PA", "stars": 3.5, "latitude": 39.962440000000001, "type": "business"}

有人可以帮我找到匹配这个模式的正则表达式吗?

4

2 回答 2

0

那应该是一个非常简单的替换。

String in = "[\"Cheesesteaks\",\"Sandwiches\", \"Restaurants\"]";
String out = in.replaceAll(", ?", "");
System.out.println(out);

["Cheesesteaks""Sandwiches""Restaurants"]
于 2013-02-19T11:09:50.520 回答
0

试试这个:

Pattern outer = Pattern.compile("\\[.*?\\]");
Pattern inner = Pattern.compile("\"\\s*,\\s*\"");
Matcher mOuter = null;
Matcher mInner = null;

mOuter = outer.matcher(jsonString);
StringBuffer sb = new StringBuffer();

while (mOuter.find()) {
    mOuter.appendReplacement(sb, "");
    mInner = inner.matcher(mOuter.group());
    while (mInner.find()) {
        mInner.appendReplacement(sb, "\"\"");
    }
    mInner.appendTail(sb);
}
mOuter.appendTail(sb);

System.out.println(sb.toString());

并替换jsonString为您的输入。

于 2013-02-19T12:18:12.383 回答