Page 1 of 1

Removing Whitespace With Perl

Posted: Fri Dec 02, 2005 4:42 am
by Grim...
Grr! :evil: ARGH!

Stoopid Perl! Stoopid whitespace!

I need to remove whitespace from my string, but not newlines, or spaces between words.

So that

Code: Select all

this is
                    my string
becomes

Code: Select all

this is
my string
Any ideas?

<edit>
The closest I've come is

Code: Select all

sub trimwhitespace($)
{
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}
but that just takes the whitespace from the beginning or end of the string, not the middle :(

Posted: Fri Dec 02, 2005 5:01 am
by Grim...
Well, I did it by splitting the string into an array at newlines and then running that trimwhitespace fucntion - the code:

Code: Select all

sub killwhitespace ($)
{
	my $string = shift;
	my @pa = split(/\n/, $string );
	foreach (@pa){
		$_ = trimwhitespace($_);
	} 
	$string = join("\n", @pa); 

	return $string ;
}

sub trimwhitespace($)
{
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}

Posted: Fri Dec 02, 2005 6:08 am
by onion2k
This works in the Regex Coach.

Code: Select all

s/[\t ]{2}//g
EDIT: Argh .. no it doesn't .. my test just happened to have odd numbers of spaces. It fails if there's an even number. Back to the drawing board.

EDIT 2: Right..

Code: Select all

s/[\t ]+/ /g
s/^ //mg
s/ $//mg
Shame it's 3 patterns rather than a nice elegant single pattern, but it does work (in the Regex Coach).

Posted: Fri Dec 02, 2005 6:26 am
by Chris Corbyn

Code: Select all

#!/bin/perl

$string = "
           some space here
        and a new line
     here          ";

$string =~ s/^[\s]+|[\s]+$//gm;

print $string;
Had to make a post :)

Posted: Sat Dec 03, 2005 12:17 am
by n00b Saibot
won't this only remove whitespace from start & end of the string only :?

Posted: Sat Dec 03, 2005 7:39 am
by Chris Corbyn
n00b Saibot wrote:won't this only remove whitespace from start & end of the string only :?
No it's in "multiline" mode... ^ and $ now represent start and end of line ;)

EDIT | That's what the "m" modifier does

Re: Removing Whitespace With Perl

Posted: Wed May 26, 2010 1:09 pm
by subychick88
I found the answer to removing white space in the middle of an array in Perl!

All you need is this regular expression:
s/\s+/ /g;

This is my code:
foreach $OUTPUTFILE (@OUTPUTFILE)
{
#removes white space from the middle of strings and replaces it with commas
$OUTPUTFILE =~ s/\s+/,/g;
print OUTPUTFILE ($OUTPUTFILE);
}

I found it on this website:
http://www.nntp.perl.org/group/perl.beg ... 01365.html

Re: Removing Whitespace With Perl

Posted: Wed May 26, 2010 4:38 pm
by John Cartwright
You do realize this thread is 5 years old. :roll: