I thought to share this relatively smart problem with everyone here. I am trying to remove unbalanced/unpaired double-quotes from a string.
My work is in progress, I might be close to a solution. But, I didn't get a working solution yet. I am not able to delete the unpaired/unpartnered double-quotes from the string.
Example Input
string1=injunct! alter ego."
string2=successor "alter ego" single employer" "proceeding "citation assets"
Output Should be
string1=injunct! alter ego.
string2=successor "alter ego" single employer proceeding "citation assets"
This problem sound similar to Using Java remove unbalanced/unpartnered parenthesis
Here is my code so far(it doesn't delete all the unpaird double-quotes)
private String removeUnattachedDoubleQuotes(String stringWithDoubleQuotes) {
String firstPass = "";
String openingQuotePattern = "\\\"[a-z0-9\\p{Punct}]";
String closingQuotePattern = "[a-z0-9\\p{Punct}]\\\"";
int doubleQuoteLevel = 0;
for (int i = 0; i < stringWithDoubleQuotes.length() - 3; i++) {
String c = stringWithDoubleQuotes.substring(i, i + 2);
if (c.matches(openingQuotePattern)) {
doubleQuoteLevel++;
firstPass += c;
}
else if (c.matches(closingQuotePattern)) {
if (doubleQuoteLevel > 0) {
doubleQuoteLevel--;
firstPass += c;
}
}
else {
firstPass += c;
}
}
String secondPass = "";
doubleQuoteLevel = 0;
for (int i = firstPass.length() - 1; i >= 0; i--) {
String c = stringWithDoubleQuotes.substring(i, i + 2);
if (c.matches(closingQuotePattern)) {
doubleQuoteLevel++;
secondPass = c + secondPass;
}
else if (c.matches(openingQuotePattern)) {
if (doubleQuoteLevel > 0) {
doubleQuoteLevel--;
secondPass = c + secondPass;
}
}
else {
secondPass = c + secondPass;
}
}
String result = secondPass;
return result;
}