To LUGNET HomepageTo LUGNET News HomepageTo LUGNET Guide Homepage
 Help on Searching
 
Post new message to lugnet.off-topic.geekOpen lugnet.off-topic.geek in your NNTP NewsreaderTo LUGNET News Traffic PageSign In (Members)
 Off-Topic / Geek / 2237
2236  |  2238
Subject: 
Re: Strip surplus white space with Perl
Newsgroups: 
lugnet.off-topic.geek
Date: 
Sun, 29 Oct 2000 16:17:03 GMT
Viewed: 
85 times
  
In lugnet.off-topic.geek, Christopher Lindsey writes:
"Fredrik Glöckner" wrote:

Hi, I'm looking into a quick and simple way to strip off all surplus
white space from a string with Perl.  If two consecutive characters
are <SPACE> and <RET>, for example, it doesn't matter to me which one
is preserved and which one is chopped off.  Any suggestions?

What about something like

  while ($string =~ s/(\s\s+)/substr($&,1,1)/e) {}

?  That should replace all whitespace ([ \t\n\r\f]) that's repeated
one or more times (that's the first part of the expression) with the
first character matching in that string.  The while() loop does it
until there aren't any more matches.

Chris

Actually, I think a simpler way is:
$string =~ s/(\s)\s+/$1/g;

The 'g' option at the end of the regexp will actually just do the replace
everywhere in the string that it can, with no real need to loop... Ain't
TMTOWTDI great? :)

DaveE



Message has 1 Reply:
  Re: Strip surplus white space with Perl
 
(...) Ahh, but what happens if you have a carriage return followed by a space? The second method eliminates the space and leaves the carriage return, which isn't what he asked for. He wanted a way to replace multiple instances of similar whitespace (...) (24 years ago, 29-Oct-00, to lugnet.off-topic.geek)

Message is in Reply To:
  Re: Strip surplus white space with Perl
 
(...) What about something like while ($string =~ s/(\s\s+)/substr($&,1,1)/e) {} ? That should replace all whitespace ([ \t\n\r\f]) that's repeated one or more times (that's the first part of the expression) with the first character matching in that (...) (24 years ago, 29-Oct-00, to lugnet.off-topic.geek)

10 Messages in This Thread:



Entire Thread on One Page:
Nested:  All | Brief | Compact | Dots
Linear:  All | Brief | Compact

This Message and its Replies on One Page:
Nested:  All | Brief | Compact | Dots
Linear:  All | Brief | Compact
    

Custom Search

©2005 LUGNET. All rights reserved. - hosted by steinbruch.info GbR