Amila Fonseka
Amila Fonseka

Reputation: 402

Best way to replace a special word in java

In my current project, I have requirement to replace a word with a value in a paragraph.

Ex :

"Event name is {[Event].[Name]} Contact name is {[Contact].[Name]}"

In the above line, '{[Event].[Name]}' should be replaced by the event name. The first part is an object (event). There are different objects. The second part (name) is a property of the object.

I have the Objects and relevant property values with me.

Can someone please tell me the best way to do this?

Should I use regex, a for loop or something else?

Upvotes: 0

Views: 151

Answers (3)

OneCricketeer
OneCricketeer

Reputation: 191738

Something like this?

String.format("Event name is %s. Contact name is ‰s", event.getName(), contact.getName()) ;

If you need something more complex than that, use Velocity or FreeMarker templates

Upvotes: 1

Mikenno
Mikenno

Reputation: 294

Something like this should for for replacing it, but there is better ways to define the regex expression

String str = "Event name is {[Event].[Name]}";

String eventStr = "event";

String nameStr = "name";

str = str.replaceAll(Pattern.quote("{[Event].[Name]}"), String.format("%s.%s", eventStr, nameStr));

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44834

a simple String replace (or two)

str = str.replace ("{[Event].", value1).replace ("[Name]}", value2);

Not sure if you wanted the . replaced or not

Upvotes: 0

Related Questions