vb.net string - replace placeholder tokens efficiently -


i'm looking ideas little problem. i've string that's template message, example:

dear [[guest.firstname]],  hope looking forward holiday in [[booking.resortname]] 

my current system replacing spaceholder tokens (e.g. [[guest.firstname]]) inefficient, there's loops inside loops , takes long.

what i'm looking way go through string until finds [[something]], replace [[something]] it's real value, continue on through string.

please note replace [[something]] need have access space holder (i.e. need know if it's [[guest.firstname]] or [[booking.resortname]]).

any suggestions efficient way achieve appreciated, feel should straightforward can think of ends loops inside loops again.

thanks!

phil.

there many factors affect performance, it's hard say, without knowing specifics, method efficient. however, when comes coding simplicity, using regex matchevaluator excellent option. i'm sure you'll agree it's cleaner whatever using:

public function replaceplaceholders(data string) string     dim r new regex("\[\[(?<placeholder>.*?)\]\]")     data = r.replace(data, new matchevaluator(addressof placeholderreplacementevaluator)) end function  private function placeholderreplacementevaluator(match match) string     dim name string = match.groups("placeholder").value     return lookupvaluebyplaceholdername(name)   ' replace value lookup logic here end function 

if total number of placeholders in data going rather small, , list of possible placeholders small, it's best have list of them values , replace them this:

public function replaceplaceholders(data string) string     dim placeholders dictionary(of string, string) = loadplaceholders()     each keyvaluepair(of string, string) in placeholders         data = data.replace(i.key, i.value)     next     return data end function  private function loadplaceholders() dictionary(of string, string)     dim placeholders new dictionary(of string, string)     ' load data here     return placeholders end function 

if want efficient solution, though, going character character , appending, go, stringbuilder or output stream, going best option. it's not going pretty, if post have codereview, there may people find ways of making less ugly :)


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -