How to replace a regexp group with a post proceed value?

荒凉一梦 提交于 2019-12-02 14:45:08

问题


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?


回答1:


Use appendReplacement/appendTail:

StringBuffer output = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(output, SelectRandomFromTemplate(matcher.group(1), count)); 
}
matcher.appendTail(output);
return output.toString(); 


来源:https://stackoverflow.com/questions/2966657/how-to-replace-a-regexp-group-with-a-post-proceed-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!