Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang Replacing substring in string

Tags:

string

erlang

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 :)

like image 428
nikdange_me Avatar asked Jan 05 '23 07:01

nikdange_me


2 Answers

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.

like image 145
Yoshihiro Tanaka Avatar answered Jan 06 '23 20:01

Yoshihiro Tanaka


If that's your specific use case- changing the filename- you can do something like this:

1> filename:dirname("/user/home/file_name1.txt") ++ "/" ++ "file_name2.txt".
"/user/home/file_name2.txt"
2>
like image 32
Derek Brown Avatar answered Jan 06 '23 19:01

Derek Brown