gstackoverflow gstackoverflow - 5 months ago 8
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

"number","number","someValues","digit"


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.

P.S.

my variant:

String valuePattern = "\\[(.*?)\\]";
Pattern valueR = Pattern.compile(valuePattern);
Matcher valueM = valueR.matcher(line);
List<String> list = new ArrayList<String>();
while (valueM.find()) {
list.add(valueM.group(0));
}
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;
}
System.out.println(value);

Answer

EDITED

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.*;
import java.io.*;

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()){
  if(m.group(2)!=null){
    m.appendReplacement(s, "[\""+m.group(2)+"\"");
  }else if(m.group(4)!=null){
    m.appendReplacement(s, ",\""+m.group(4)+"\"");
  }
}
m.appendTail(s);
print(s);