Is there an optimized way to match and replace multiple substrings at the same time?

For example, to replace {{A}} with content A and {{B}} with content B (guaranted that no other matching substring appears in the replaced content). Using string.replace("{{A}}", "content A").replace("{{B}}", "content B") directly reconstructs the string several times, is there a more efficient way?

Regular expressions, via the regex crate:

use regex::Regex;

let re = Regex::new(r"\{\{(\w+)\}\}").unwrap();
let s_replaced = re.replace_all(s, "content $1");

Playground

regex is not a tiny dependency and introduces a lot of unrelated code. Is there a way to have fewer dependencies?

1 Like

Yes. You can do it with multiple scans. If you only need to do it, say, twice on a tiny haystack, then that's probably fine.

If you've benchmarked it and know that you'd materially benefit from doing the replacement more quickly, and all of your needles are just literal strings, you do not need to bring in the regex crate. You can use AhoCorasick::replace_all from the aho-corasick crate.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.