nabil chouaib
nabil chouaib

Reputation: 135

How to extract integer from a string in 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.

Upvotes: 6

Views: 7757

Answers (2)

ravnur
ravnur

Reputation: 2852

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).

Upvotes: 1

tow
tow

Reputation: 569

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)

Upvotes: 9

Related Questions