String Function
Does anyone know the most efficient way to parse a string like this:
"value1:subvalue1, value2, value3:subvalue3"
and extract a sting containing a comma separated list of the values e.g.
"value1,value2,value3"
and a comma separated list of the subvalues e.g.
"subvalue1,,subvalue3"
I am using the following code is ther a better / neater / more efficient way of doing this?
public class StringParser {
private String getSummaryHeaderValues() {
String summaryHeader = "date:com.lb.cmte.data.cf.services.oes.netrev.utils.DateFormatter[MM/dd/yyyy],ListID,Client,StrikeTypeName,PortfolioType,NumSymbols,NumShares,GrossRevenue,DollarValue,ImplicitComm,Loss,NetRev";
String[] headerParts = summaryHeader.split(",");
StringBuffer rebuiltString = new StringBuffer();
int i = 0;
for (String headerPart : headerParts) {
if (headerPart.contains(":")) {
headerPart = headerPart.substring(0, headerPart.indexOf(":"));
}
rebuiltString.append(headerPart);
if (i < headerParts.length - 1)
rebuiltString.append(",");
i++;
}
// Rebuild the string
return rebuiltString.toString();
}
private String getFormatValues() {
String summaryHeader = "date:com.lb.cmte.data.cf.services.oes.netrev.utils.DateFormatter[MM/dd/yyyy],ListID,Client,StrikeTypeName,PortfolioType,NumSymbols,NumShares,GrossRevenue,DollarValue,ImplicitComm,Loss,NetRev";
String[] headerParts = summaryHeader.split(",");
StringBuffer rebuiltString = new StringBuffer();
int i = 0;
for (String headerPart : headerParts) {
if (headerPart.contains(":")) {
headerPart = headerPart.substring(headerPart.indexOf(":") + 1, headerPart.length());
rebuiltString.append(headerPart);
} else {
rebuiltString.append(headerPart);
if (i < headerParts.length - 1)
rebuiltString.append(",");
}
i++;
}
// Rebuild the string
return rebuiltString.toString();
}
public static void main(String[] args) {
StringParser stringParser = new StringParser();
System.out.println(stringParser.getSummaryHeaderValues());
System.out.println(stringParser.getFormatValues());
}
import java.util.regex.*;
public class Test
{
public static void main(String... args)
{
String summaryHeader =
"date:com.lb.cmte.data.cf.services.oes.netrev.utils.DateFormatter[MM/dd/yyyy]," +
"ListID,Client,StrikeTypeName,PortfolioType,NumSymbols,NumShares,GrossRevenue," +
"DollarValue,ImplicitComm,Loss,NetRev";
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
if (breakDown(summaryHeader, sb1, sb2))
{
String headers = sb1.toString();
String formats = sb2.toString();
System.out.printf("%n%s%n%s%n", headers, formats);
}
}
public static boolean breakDown(String header, StringBuilder result1, StringBuilder result2)
{
Pattern p = Pattern.compile("([^:,]++)(:([^:,]++),?+)?");
Matcher m = p.matcher(header);
boolean foundOne = false;
while (m.find())
{
if (foundOne)
{
result1.append(",");
result2.append(",");
}
result1.append(m.group(1));
result2.append(m.start(3) != -1 ? m.group(3) : "");
foundOne = true;
}
return foundOne;
}
}