This works for ${VAR}:
Pattern.compile("\\$\\{(.+?)\\}");
But I am struggling to format it so that it also accepts $VAR to the next word boundry (\b). Because the text can be
$FIRSTVAR.${SECONDVAR}LITERAL
and then I want to detect both $FIRSTVAR and ${SECONDVAR} and if the first is “X” and the second if “Y”, I want to replace it to X.YLITERAL. The template uses both $VAR and ${VAR} styles, prefers the former if the var is followed with a non-word character but uses the latter if it is (just like in the example I gave above).
I tried
Pattern.compile("\\$(\\{|)(.+?)(\\}|\b})");
But that matches FIRSTVAR.${SECONDVAR as group(2). So it’s not good.
Thanks in advance
I would write:
Naturally, this means that either
matcher.group(1)ormatcher.group(2)will be the variable-name — the other will benull— so you’ll have to check both.Another, less-robust option is to write:
but then it would replace e.g.
$SECONDVAR}withYrather than withY}.Edited to add: If you’re using Java 7, I think you should be able to write
and then retrieve the variable-name using
matcher.group("varname"). (I haven’t tested that in Java, because I only have Java 6 handy, and Java 6 doesn’t support named capture-groups. But it does work in Perl.) See “Group name” in thejava.util.regex.Patternjavadoc and the javadoc forjava.util.regex.Matcher.group(java.lang.String).