简体   繁体   中英

How to replace characters in string Erlang?

I have this piece of code that gets sessionid, make it a string, and then create a set with key as eg {{1401,873063,143916},<0.16443.0>} in redis. I'm trying replace { characters in this session with letter "a".

OldSessionID= io_lib:format("~p",[OldSession#session.sid]),
StringForOldSessionID = lists:flatten(OldSessionID),
ejabberd_redis:cmd([["SADD", StringForSessionID, StringForUserInfo]]);

I've tried this:

re:replace(N,"{","a",[global,{return,list}]).

Is this a good way of doing this? I read that regexp in Erlang is not a advised way of doing things.

Your solution works, and if you are comfortable with it, you should keep it.

On my side I prefer list comprehension : [case X of ${ -> $a; _ -> X end || X <- StringForOldSessionID ] [case X of ${ -> $a; _ -> X end || X <- StringForOldSessionID ] [case X of ${ -> $a; _ -> X end || X <- StringForOldSessionID ] . (just because I don't have to check the function documentation :o)

 re:replace(N,"{","a",[global,{return,list}]). 

Is this a good way of doing this? I read that regexp in Erlang is not a advised way of doing things.

According to official documentation :

2.5 Myth: Strings are slow

Actually, string handling could be slow if done improperly. In Erlang, you'll have to think a little more about how the strings are used and choose an appropriate representation and use the re module instead of the obsolete regexp module if you are going to use regular expressions.

So, either you use re for strings, or:

leave { behind(using pattern matching) if, say, N is {{1401,873063,143916},<0.16443.0>}, then

{{A,B,C},Pid} = N

And then format A,B,C,Pid into string.

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, "{", "a", all).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM