这个正则表达式意味着什么[^}] *

时间:2015-05-10 13:26:32

标签: java regex

这是我在论坛上阅读的代码。

public String replaceVariables(String input, Map<String, String> context) {
    if(context == null || input == null)
        return input;

    Matcher m = Pattern.compile( "\\$\\{([^}]*)\\}" ).matcher( input );
    // Have to use a StringBuffer here because the matcher API doesn't accept a StringBuilder -kg
    StringBuffer sb = new StringBuffer();
    while(m.find()) {
        String value = context.get(m.group(1));
        if(value != null)
            m.appendReplacement(sb, value);
    }
    m.appendTail(sb);
    return sb.toString();
}

我对[^}]*感到困惑。我可以使用其他字符代替}吗?

1 个答案:

答案 0 :(得分:5)

[]在正则表达式中用于表示一组字符。

^表示运算符。但请注意,如果^不是集合中的第一个字符,则不会将其视为操作,而是视为字符。例如,[1^2]匹配1^2(不是1以及任何不属于2的内容(感谢@Maroun Maroun

因此,[^}]表示由 }的字符组成的一组字符。

*表示该集合可以有无限(包括零)重复。