[erlang-questions] How best to resolve apparent inconsistency between re:run and string:slice
Dan Sommers
2QdxY4RzWzUUiLuE@REDACTED
Thu Aug 29 10:36:32 CEST 2019
On 8/29/19 2:59 AM, Scott Finnie wrote:
> What I’m trying to achieve is consistent behaviour that (a) recognises
> any newline (CR, LF, CRLF, …) at the start of the string and removes
> it. I also need a count of the contiguous newlines found.
Regular expressions seem needlessly complicated for this task. I'd use
something more direct. Assuming that you want to count CRs and LFs
separately, and not recognize CRLF as a single new line:
%% return a {String, Counter} tuple where the leading CRs and LFs
%% have stripped from String and counted in Counter
count_and_strip_leading_crs_and_lfs(String) ->
count_and_strip_leading_crs_and_lfs(String, 0).
count_and_strip_leading_crs_and_lfs([$\r | String], Counter) ->
count_and_strip_leading_crs_and_lfs(String, Counter + 1);
count_and_strip_leading_crs_and_lfs([$\n | String], Counter) ->
count_and_strip_leading_crs_and_lfs(String, Counter + 1);
count_and_strip_leading_crs_and_lfs(String, Counter) ->
{String, Counter}.
To count CRLFs as a single new line, add this to the beginning of
count_and_strip_leading_crs_and_lfs/2:
count_and_strip_leading_crs_and_lfs([$\r, $\n | String], Counter) ->
count_and_strip_leading_crs_and_lfs(String, Counter + 1);
HTH,
Dan
More information about the erlang-questions
mailing list