I need to create a regular expression that will remove all extra whitespace from a text document with the exception of spaces and new lines. The document is read into a variable and I then perform a search and replace using regexp. Unfortunately I haven't been able to remove all of the extra whitespace with a single regexp command. Is it possible to use a single regexp statement to accomplish all of the following tasks?
* remove all whitespace other than spaces and new lines
* remove any repeating spaces that appear one after another
* limit number of new lines that appear one after another to a total of 2 (double spaced)
EXAMPLE:
"this is an {space}{space}example\n\n\t\nthis is line two"
In the example above I would need to remove the two extra spaces, the tab, and one of the new lines. The simplest way to remove extra whitespace would be to use something like this
/[\t\v\f\r]|\s(?=\s)/ and then just replace the occurrences with an empty string. However, I need to preserve some spaces and new lines so I'm unable to use \s and the statement above doesn't catch all unicode whitespace characters.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.