我需要解析下面给出的几行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"}
有人可以帮我找到符合这种模式的正则表达式吗?
答案 0 :(得分:0)
这应该是一个非常简单的替代品。
String in = "[\"Cheesesteaks\",\"Sandwiches\", \"Restaurants\"]";
String out = in.replaceAll(", ?", "");
System.out.println(out);
给出
["Cheesesteaks""Sandwiches""Restaurants"]
答案 1 :(得分: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
。