What is the best method for string replacement

I have a file that I want to read in and replace some values in real time. If I have a sample file which I read into a string.

Hello {{username}}
There are {{num_users}} currently online at {{time}}. 

I want to replace {{username}} with "John" and {{num_users}} with "72" and {{time}} with a timestamp ?

What is the best way to do this? simple regex, or as crate like askama or tera or handlebars ?

What would you recommend ?

The standard library has a method called replace which can do it.

But if you need to replace multiple things it will be inefficient as it will loop over the string multiple times, and allocate and copy multiple times.

Is the file available at compile time?

Yes, the file would be available at compilation.

If that is the case, and speed matters, I'd use askama or display-as or even just convert the file into an inline rust string literal and use print!().

I've had a good experience with i18n-embed if you need a lot of different templates, but it requires a bit of setup to get working.

I'd start with a \{\{(.+?)\}\} regex replace. It's easy, it's one-pass, and it'll be pretty fast.

The extra complexity to go faster than that would be pretty high.

3 Likes

I have been busy making templates and the largest on so far has 18 substitutions. So I think I'm going to go with one of the templating systems rather than regex. But which one is easiest for a beginner?