iburrell has asked for the wisdom of the Perl Monks concerning the following 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.
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.$main::stateIn{'address'} =~ s/(?<=[^\015])[\012\015](?=[^\012])/\015\ +012/g;
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;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•Re: Line ending transformation
by merlyn (Sage) on Feb 28, 2003 at 20:44 UTC | |
by iburrell (Chaplain) on Feb 28, 2003 at 20:50 UTC | |
by merlyn (Sage) on Feb 28, 2003 at 20:55 UTC | |
|
Re: Line ending transformation
by OM_Zen (Scribe) on Feb 28, 2003 at 21:02 UTC | |
|
Re: Line ending transformation
by OM_Zen (Scribe) on Feb 28, 2003 at 21:11 UTC | |
by Hofmator (Curate) on Mar 01, 2003 at 09:04 UTC |