radlan
radlan

Reputation: 2563

Replace only part of a string with velocity

I found no way to replace only parts of a string with velocity.

Assume the following velocity template:

$test
something$test
$test.something

I want to replace all occurrences of $test with the string TEST.

I therefore use the following code:

  VelocityContext context = new VelocityContext();
  context.put("test", "TEST");

This is the result, I expect:

TEST
somethingTEST
TEST.something

But what I really get is:

TEST
somethingTEST
$test.something

So obviously Velocity doesn't replace a variable if there is some text after the variables name.

What can I do to replace a variable even if it is only a part of a string?

Upvotes: 1

Views: 1889

Answers (2)

Jay
Jay

Reputation: 1119

The $test.something is causing the problem.

It is expecting a variable something inside the object test.

Use ${test}.something instead...

--Cheers, Jay

Upvotes: 3

anil gopalakrishna
anil gopalakrishna

Reputation: 90

The problem you face here is not 'obviously Velocity doesn't replace a variable if there is some text after the variables name'.

The symbol '$' is used to represent beginning of any line. So you have to find a way to escape that symbol in the input string so that the literal meaning of '$' is not considered

Upvotes: 0

Related Questions