I have a string in which I have placeholders such as @parent and @email. I want to replace those placeholders with some value.
For e.g:
Dear @parent, your email is @email
will be transformed as
Dear parent_name, your email is email_address
I am using the following code to replace @parent with a string. But it is not replacing the pattern.
String messageBody = "Dear @parent,how are you";
messageBody = messageBody.replaceAll("\\b@parent\\b", massCommunicationMessageWrapper.getParentName());
If I use the following code it replaces the pattern
String messageBody = "Dear @parent,how are you";
messageBody = messageBody.replaceAll("\\bparent\\b", massCommunicationMessageWrapper.getParentName());
What regex should be written to replace the word "@parent"?
>Solution :
The definition fo \b
states:
…
There are three different positions that qualify as word boundaries:
- Before the first character in the string, if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in the string, where one is a word character and the other is not a word character.
…
Our "word" ("@parent"
) does not start with a word character. Therefore, the leading \b
does not match since there is a non-word character (a blank) on the left and a non-word character (an @
) on the right.
I would suggest to remove the leading \b
:
String messageBody = "Dear @parent,how are you";
messageBody = messageBody.replaceAll("@parent\\b", massCommunicationMessageWrapper.getParentName());
Noteworthy behaviour
Notice that the current implementation does allow for "chaining" multiple placeholders right next to each other, i.e.
"@first@second@third"
would process with the current regular expression schema if @first
, @second
and @thirs
are separate variables.
Furthermore, the current solution does replace something like "Dear@parent, how are you?"
(note the missing blank between "Dear"
and "@parent"
).
Finally, the input "Dear @parentign"
would not be processed when we want to replace "@parent"
.
Closing comment
For more complex scenarios, I recommend using a solution backed by a template engine, e.g. freemarker.