0

我有这个代码

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;
    }

输入是:

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

输出示例:

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

我想用该方法返回的选取值替换 {} 组模板。我如何在 Java1.5 中做到这一点?

4

1 回答 1

3

使用appendReplacement/ appendTail

StringBuffer output = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(output, SelectRandomFromTemplate(matcher.group(1), count)); 
}
matcher.appendTail(output);
return output.toString(); 
于 2010-06-03T14:08:03.940 回答