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 :)
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With