Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract integer from a string in Erlang?

Tags:

erlang

I have this variable Code in erlang which has this value "T00059"

I want to extract this value 59 from Code.

I try to extract with this code this value "00059".

NewCode = string:substr(Code, 2, length(Code)),

Now I want to know how can we eliminate the first zero before the first integer not null. I mean how can we extract "59"?

For example if I have this value "Z00887" I should have in the final this value 887.

like image 747
nabil chouaib Avatar asked Feb 11 '13 21:02

nabil chouaib


2 Answers

You can simply do (output from an interactive erlsession):

1> Code = "Z00887",
1> {NewCode, _Rest} = string:to_integer(string:substr(Code, 2, length(Code))),
1> NewCode.
887

(My answer in test with loop in erlang goes into more detail regarding the same problem)

like image 145
tow Avatar answered Sep 21 '22 23:09

tow


This code will skip starting zeros. If you want to save them change $1 to $0

extract_integer([]) -> [];
extract_integer([H|T]) when (H >= $1) and (H =< $9) -> [H] ++ T;
extract_integer([_H|T]) -> extract_integer(T).
like image 25
ravnur Avatar answered Sep 21 '22 23:09

ravnur