【问题标题】:How to replace a regexp group with a post proceed value?如何用后处理值替换正则表达式组?
【发布时间】:2010-06-03 14:01:16
【问题描述】:

我有这个代码

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 中如何做到这一点?

【问题讨论】:

    标签: java regex matcher


    【解决方案1】:

    使用appendReplacement/appendTail:

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

    【讨论】:

    • Java 7 最终将允许为此使用 StringBuilder。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    相关资源
    最近更新 更多