Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to replace tokens in a large text template

Tags:

c#

.net

I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use String.Replace(), but is there a better, more efficient way or is Replace() already optimized for this?

like image 203
jeremcc Avatar asked Aug 21 '08 15:08

jeremcc


People also ask

How to apply the same replacement to multiple tokens in string?

We might easily apply the same replacement to multiple tokens in a string with the replaceAll method in both Matcher and String. In this tutorial, we'll explore how to apply a different replacement for each token found in a string.

How do you format a token in a snippet?

Tokens in every snippet must be properly formatted. A token cannot start in one snippet then end in another. For example, you cannot insert a text that contains only the beginning of a token (e.g., “Hello {”) then append a text with the end of the token (e.g., “USERNAME}.”).

What are tokens used for in Python?

Tokens. Tokens are recognized in text every time a new text is added (by the Append, Replace, InsertBefore, and InsertAfter functions). Positions of tokens are kept in a Dictionary for fast retrieval. That way searching for a text to be replaced takes O(n*log(n) + m) time instead of O(n*m).

How do you get all the tokens in a regular expression?

Use a Function and Pattern Input We can use a Java Function<Matcher, String> object to allow the caller to provide the logic to process each match. And we can take an input called tokenPattern to find all the tokens: Here, the regular expression is no longer hard-coded.


1 Answers

System.Text.RegularExpressions.Regex.Replace() is what you seek - IF your tokens are odd enough that you need a regex to find them.

Some kind soul did some performance testing, and between Regex.Replace(), String.Replace(), and StringBuilder.Replace(), String.Replace() actually came out on top.

like image 139
Greg Hurlman Avatar answered Oct 09 '22 06:10

Greg Hurlman