gstackoverflow gstackoverflow - 1 year ago 49
Java Question

How to replace a string with a regex in java using nested groups

I have the format line

"123","45","{"VFO":[B501], "AGN":[605,B501], "AXP":[665], "QAV":[720,223R,251Q,496M,548A,799M]}","4"

it can be longer but it always contains


I need to wrap values inside someValues with quotes

for test string expected result should be.

"123","45","{"VFO":["B501"], "AGN":["605","B501"], "AXP":["665"], "QAV":["720","223R","251Q","496M","548A","799M"]}","4"

Please suggest simplest solution in java.


my variant:

String valuePattern = "\\[(.*?)\\]";
Pattern valueR = Pattern.compile(valuePattern);
Matcher valueM = valueR.matcher(line);
List<String> list = new ArrayList<String>();
while (valueM.find()) {
String value = "";
for (String element : list) {
element = element.substring(1, element.length() - 1);
String[] strings = element.split(",");
String singleGroup = "[";
for (String el : strings) {
singleGroup += "\"" + el + "\",";
singleGroup = singleGroup.substring(0, singleGroup.length() - 1);
singleGroup = singleGroup + "]";
value += singleGroup;

Answer Source


OK, here is the shortest way i found, it works very nicely in my opinion, except for the comma and the bracket which i had to add manually... somebody might be able to do it straight away but i found it tricky to handle replacements with nested groups.

import java.util.*;
import java.lang.*;

Pattern p = Pattern.compile("(\\[(\\w+))|(,(\\w+))");
Matcher m = p.matcher("\"123\",\"45\",\"{\"VFO\":[B501], \"AGN\":[605,B501], \"AXP\":[665], \"QAV\":[720,223R,251Q,496M,548A,799M]}\",\"4\"");
StringBuffer s = new StringBuffer();
while (m.find()){
    m.appendReplacement(s, "[\"""\"");
  }else if(!=null){
    m.appendReplacement(s, ",\"""\"");