views:

18

answers:

1

I have this code to

public static String ProcessTemplateInput(String input, int count) {
        Pattern pattern = Pattern.compile("\\{([^\\}]+)\\}");
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            String newelem=SelectRandomFromTemplate(matcher.group(1), count);
        }
        return input;
    }

Input is:

 String s1 = "planets {Sun|Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune}{?|!|.} Is this ok? ";

Output example:

String s2="planets Sun, Mercury. Is this ok? ";

I would like to replace the {} set of templates with the picked value returned by the method. How do I do that in Java1.5?

+3  A: 

Use appendReplacement/appendTail:

StringBuffer output = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(output, SelectRandomFromTemplate(matcher.group(1), count)); 
}
matcher.appendTail(output);
return output.toString(); 
axtavt
+1; one of the few places I'd use `StringBuffer`.
polygenelubricants
Java 7 will finally allow the use of StringBuilder for this.
Alan Moore