First the rant, then the question.

Some code I am maintaining has a really bad regular expression for canonicalizing line endings. It is supposed to process a potentially multi-line input field and canonicalize changed the line ending to CRLF.

$main::stateIn{'address'} =~ s/(?<=[^\015])[\012\015](?=[^\012])/\015\ +012/g;
Can anyone spot the problem? It removes the character before and after the line ending. This is a big problem when the second line is an address and "1201 Some St" turns into "201 Some St". The package goes to the wrong address and the customer doesn't get his order.

The question: what is the best regular expression for transforming line endings characters. It should handle Windows (\015\012), Unix (\012), and Mac (\015). It should turn them into \n, and the one that Perl handles best.

This is easy when the line endings of the input is known, like with the standard DOS to Unix: s/\r\n/\n/g. It is much harder to get right when the format is unknown like with web forms. One problem area is multiple blank lines. The first attempt I tried with look-ahead and look-behind fails with blank lines:

s/(?<=[^\015])[\012\015](?=[^\012])/\015\012/g;

In reply to Line ending transformation by iburrell

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.