So, I have a string. Most of the time, if the string has square brackets in it, bad things will happen. In a few cases, however, it's necessary to keep the brackets. These brackets that need to be kept are identified by a certain prefix. E.g., if the string is:
apple][s [pears] prefix:[oranges] lemons ]persimmons[ pea[ches ap]ricots [][[]]][]
what I want to turn it into is:
apples pears prefix:[oranges] lemons persimmons peaches apricots
I've come up with a Rube Goldberg mess of a solution, which looks like this:
public class Debracketizer
{
public static void main( String[] args )
{
String orig = "apples [pears] prefix:[oranges] lemons ]persimmons[ pea[ches ap]ricots";
String result = debracketize(orig);
System.out.println(result);
}
private static void debracketize( String orig )
{
String result1 = replaceAll(orig,
Pattern.compile("\\["),
"",
".*prefix:$");
String result2 = replaceAll(result1,
Pattern.compile("\\]"),
"",
".*prefix:\\[[^\\]]+$");
System.out.println(result2);
}
private static String replaceAll( String orig, Pattern pattern,
String replacement, String skipPattern )
{
String quotedReplacement = Matcher.quoteReplacement(replacement);
Matcher matcher = pattern.matcher(orig);
StringBuffer sb = new StringBuffer();
while( matcher.find() )
{
String resultSoFar = orig.substring(0, matcher.start());
if (resultSoFar.matches(skipPattern)) {
matcher.appendReplacement(sb, matcher.group());
} else {
matcher.appendReplacement(sb, quotedReplacement);
}
}
matcher.appendTail(sb);
return sb.toString();
}
}
I'm sure there must be a better way to do this -- ideally with one simple regex and one simple String.replaceAll()
. But I haven't been able to come up with it.
(I asked a partial version of this question earlier, but I can't see how to adapt the answer to the full case. Which will teach me to ask partial questions.)