-2

I need to parse several rows of the type of JSON code given below. I need to remove all the commas(,) which are inside square brackets. That is ["Cheesesteaks","Sandwiches", "Restaurants"] becomes ["Cheesestakes""Sandwiches""Restaurants"]. I need to preserve all the other commas as they are.

Another example - ["Massachusetts Institute of Technology", "Harvard University"] would become ["Massachusetts Institute of Technology""Harvard University"] keeping all other commas intact.

{"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"}

Can someone please help me find the regular expression to match this pattern?

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
Josh Cher Man
  • 33
  • 1
  • 3

2 Answers2

0

That should be a very simple replace.

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

Gives

["Cheesesteaks""Sandwiches""Restaurants"]
Tom
  • 15,798
  • 4
  • 37
  • 48
0

Try this:

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());

And replace jsonString with your input.