Pages

13/07/2013

[Java 4] Replace placeholder word in string

Should you be unlucky and have to work with Java 4, you may find it lacking many of the convenient features found in later versions.

One of them is the ability to replace a placeholder word in a String with little effort. What you can do is use the replaceAll method:

String str = "some string with a #placeholder# inside";
str=str.replaceAll("#placeholder#", "value");

Note that it will search for and replace ALL matches it finds, making it viable as a placeholder substitution method while it's pretty useless if you have to replace a single word; in that case, you may find the replaceFirst method more suitable.

Remember in any case that the first parameter is parsed as a regular expression meaning that you'll have to escape reserved characters such as "$" if your placeholder contains them. Another very important thing to remember is that, since String objects are immutable in Java, if you don't assign the return value to some variable, the substitution won't have any effect.
 

No comments:

Post a Comment

With great power comes great responsibility