-1

This is a code I read on a forum.

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

I am confuse about [^}]*. Can I use another character instead of }?

elixenide
  • 42,388
  • 14
  • 70
  • 93
Hikaru
  • 23
  • 1
  • 4

1 Answers1

5

The [] is used in regular expression to denote a set of characters.

The ^ denotes the not operator. However, note that if the ^ is not the first character in the set, it won't be treated as an operation, but rather as a character. For example, [1^2] matches 1, ^ and 2 (not 1 and anything that's not 2) (thanks to @Maroun Maroun)

Therefore, [^}] denotes a set of characters that's comprised of characters which are not }.

The * means that there can be infinite (including zero) repetitions of the set.

Community
  • 1
  • 1
Konstantin Yovkov
  • 59,030
  • 8
  • 92
  • 140
  • 1
    Good answer, but you might add that the `*` allows for zero repetitions. I.e., there don't have to be any non-`}` characters at all for the regex to match the string. – elixenide May 10 '15 at 13:53
  • 1
    Also note that if `^` is not the first character, it'll loose its meaning. For example, `[1^2]` matches 1, ^ and 2 (not 1 and anything that's not 2). – Maroun May 10 '15 at 14:23
  • Thanks, Maroun. Added that too. :) – Konstantin Yovkov May 10 '15 at 14:27