加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Erlang正则解析操作文件

发布时间:2020-12-14 01:44:56 所属栏目:百科 来源:网络整理
导读:-module(tool). %% ==================================================================== %% API functions %% ==================================================================== -export([modify_hostname/0,modify_ip/0]). modify_hostname() - {

-module(tool).
%% ====================================================================
%% API functions
%% ====================================================================
-export([modify_hostname/0,modify_ip/0]).
modify_hostname() ->
{ok,HostName} = inet:gethostname(),
%通过截取和添加,得到priv所在的目录
EbinDir = filename:dirname(code:which(?MODULE)),
ProjectDir = string:sub_string(EbinDir,1,length(EbinDir)-4),
PrivDir = ProjectDir ++ "priv/",
{ok,Files} = file:list_dir(PrivDir),
lists:foreach(fun(A)-> replace(PrivDir++A,HostName) end,Files),
io:format("modify hostname successfully!~n").
replace(FileName,HostName) ->
{ok,Content} = file:read_file(FileName),
RawString = binary_to_list(Content),
%% 以非贪婪模式匹配@开头不包含}的任意字符同时以逗号结束的特征串
{ok,MP1} = re:compile("@[^}]*,",[ungreedy]),
ResultString1 = re:replace(RawString,MP1,"@"++HostName++",[{return,list},global]),
%% 以非贪婪模式匹配@开头不包含}和逗号的任意字符同时以]}结束的特征串
{ok,MP2} = re:compile("@[^},]*]}",
ResultString2 = re:replace(ResultString1,MP2,"@"++HostName++"]},MP3} = re:compile("@[^,]*}]",
ResultString3 = re:replace(ResultString2,MP3,"@"++HostName++"}]",
file:write_file(FileName,list_to_binary(ResultString3)).

modify_ip() ->
{ok,Iflist} = inet:getif(),
{A,B,C,D} = element(1,lists:nth(2,Iflist)),
Ebin = filename:dirname(code:which(?MODULE)),
%% 得到nodefinder.app所在的路径
ProjectDir = string:sub_string(Ebin,length(Ebin)-17),
AppDir = ProjectDir ++ "Res/ebin/nodefinder.app",Content} = file:read_file(AppDir),
LocalIp = "{"++integer_to_list(A)++","++integer_to_list(B)++","++integer_to_list(C)++","++integer_to_list(D)++"}",
%% 通过正则表达式进行匹配后,然后替换成本机Ip
{ok,MP} = re:compile("{[0-9]+,[0-9]+,[0-9]+}"),
ResultString = re:replace(RawString,MP,LocalIp,list}]),
file:write_file(AppDir,list_to_binary(ResultString)),
io:format("modify ip successfully!~n").

解析的文件如下:

总结:(1)学习通过filename:dirname(code:which(?MOUDLE))获取文件所在的绝对路径;

(2)erlang的file:get_cwd(),file:list_dir("."),默认的是工作目录或是c:cd(...)后进入的目录,如果没有设定erlang的工作目录,则“.”表示当前目录;

(3)学习erlang中正则表达式的使用方法

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读