2013-02-19 58 views
-2

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

另一个示例 - ["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

试试这个:

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与您的输入。

0

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

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

给人

["Cheesesteaks""Sandwiches""Restaurants"]