Replace multiple strings in Erlang

There is no direct built-in function in Erlang to replace multiple strings, however, you can achieve similar functionality by using Erlang's string manipulation functions and pattern matching. Here is a simple example showing how to replace multiple strings in Erlang:

-module(string_replace_example).
-export([replace_each/3]).

replace_each(String, Targets, Replacements) ->
    replace_each(String, Targets, Replacements, []).

replace_each(String, [], [], _Acc) ->
    lists:concat(String);
replace_each(String, [Target | TTargets], [Replacement | TReplacements], Acc) ->
    NewString = string:replace(String, Target, Replacement),
    replace_each(NewString, TTargets, TReplacements, [NewString | Acc]).

In the above code, replace_each/3 the function takes a string String , a list of target strings Targets and a list of replacement strings Replacements . It iterates through the list of target strings and the list of replacement strings recursively, and replaces each target string with the corresponding replacement string.

Here is an example usage:

1> string_replace_example:replace_each("Hello, world!", ["Hello", "world"], ["Hi", "Erlang"]).
"Hi, Erlang!"

In the above example, replacing "Hello" with "Hi" and "world" with "Erlang" in the string "Hello, world!" results in "Hi, Erlang!".

Note that the above example can only do simple string replacements, and only in the order of the list of target strings and the list of replacement strings. If you need more complex string replacement logic, you may need to use more advanced string processing techniques or write custom replacement functions. According to specific needs and situations, choose an appropriate method to implement the string replacement function.

Supongo que te gusta

Origin blog.csdn.net/qq_25231683/article/details/131270852
Recomendado
Clasificación