Erlang替换字符串中的子字符串

gudnpqoy  于 2022-12-08  发布在  Erlang
关注(0)|答案(3)|浏览(215)

我想用Erlang中的其他文本替换字符串中的occurrence子字符串。
问题示例:我想用 file_name2 文本替换 file_name1

输入:/用户/主目录/* 文件名1 .txt
输出:/用户/主目录/
文件名2 *.txt

感谢您的回答!谢谢:)

lsmepo6l

lsmepo6l1#

您可以使用re模块。Erlang shell中的示例如下:

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>

同样,如果你要匹配大数据,re2可能会有帮助,尽管它是NIF库。

p4rjhz4m

p4rjhz4m2#

如果这是您的特定用例-更改文件名-您可以执行以下操作:

1> filename:dirname("/user/home/file_name1.txt") ++ "/" ++ "file_name2.txt".
"/user/home/file_name2.txt"
2>
kninwzqo

kninwzqo3#

Since Erlang OTP 20.0 you can use string:replace/3 function from string module.
string:replace/3 - replaces SearchPattern in String with Replacement. 3rd function parameter indicates whether the leading, the trailing or all encounters of SearchPattern are to be replaced.

string:replace(Input, "/user/home/file_name1.txt", "/user/home/file_name2.txt", all).

相关问题