Search code examples
stringerlang

Erlang Replacing substring in string


I want to replace occurrence substring in the string with some other text in erlang.

Example for the question : I want to replace file_name1 with file_name2 text.

Input : /user/home/file_name1.txt

Output : /user/home/file_name2.txt

Description with answer appreciated! Thanks :)


Solution

  • You can use re module. Example in Erlang shell below:

    12> re:replace("erlang/merl/Makefile", "Makefile", "README.md", [{return,list}]).
    "erlang/merl/README.md"
    13> re:replace("erlang/merl/Makefile", "Makefile", "README.md", [{return,binary}]).
    <<"erlang/merl/README.md">>
    14> {ok, Mp} = re:compile("Makefile").
    {ok,{re_pattern,0,0,0,
                <<69,82,67,80,87,0,0,0,0,0,0,0,81,0,0,0,255,255,255,255,
                  255,255,...>>}}
    15> re:replace("erlang/merl/Makefile", Mp, "README.md", [{return,list}]).
    "erlang/merl/README.md"
    16>
    

    Also if you're matching against large data, re2 may help. It's NIF library though.