Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

How do I remove whitespace at the beginning or end of my string?

( #2258=categorized question: print w/ replies, xml ) Need Help??
Contributed by vroom on Jan 21, 2000 at 00:44 UTC
Q&A  > regular expressions


Answer: How do I remove whitespace at the beginning or end of my string?
contributed by btrott

You could also do this in just one step. Use foreach's aliasing behavior to write this:

for ($string) { s/^\s+//; s/\s+$//; }
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by infinityandbeyond

One line is just as good.

#replace 0 or more whitespaces at the beginning # or 0 or more whitespaces at the end # with nothing $string =~ s/^\s+|\s+$//g;
Credit to perlmonkey for corrections to original post -- Ed.
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by vroom

Use substitution along with the special characters ^ and $ which match the beginning and end of strings respectively along with \s which matches whitespace;

$string=~s/^\s+//; $string=~s/\s+$//;

Edited by davido: Removed useless use of /g modifier.
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by Roy Johnson

I wrote some benchmark code to test the popular answers, and a method using just pattern match and capture instead of s///. I got good results from my pattern match, so I tried plugging my pattern into Daddio's solution (s-capture), and got a significant speedup of it (s-capture2), but still not as good as just using m//.

use Benchmark 'cmpthese'; use Regexp::Common 'whitespace'; my $f = ' this is a string with spaces to remove '; cmpthese(-3, { 'Regexp-Common' => sub { $_=$f; s/$RE{ws}{crop}//g; }, 'two-s///' => sub { $_=$f; s/^\s+//; s/\s+$//; }, 'one-s///' => sub { $_=$f; s/^\s+|\s+$//g; }, 's-capture' => sub { $_=$f; s/^\s*(.*?)\s*$/$1/; }, 's-capture2' => sub { $_=$f; s/^\s*(\S+(?:\s+\S+)?)?\s*$/$1/; }, 'm-capture' => sub { $_=$f; ($_) = /(\S+(?:\s+\S+)?)/; }, });
Rate Regexp-Common s-capture one-s/// s-capture2 m-ca +pture two-s/// Regexp-Common 659/s -- -91% -93% -95% + -96% -97% s-capture 7002/s 963% -- -21% -45% + -59% -73% one-s/// 8857/s 1244% 26% -- -30% + -48% -66% s-capture2 12699/s 1827% 81% 43% -- + -26% -51% m-capture 17179/s 2507% 145% 94% 35% + -- -34% two-s/// 25941/s 3837% 270% 193% 104% + 51% --
Not surprisingly, the straightforward method of calling s/// twice is the fastest. What is surprising is how slow Regexp-Common turns out to be, and I was pleasantly surprised at how well m-capture did. If, for some bizarre reason, you needed a single atomic expression to remove leading and trailing whitespace, that would seem to be the way to go.
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by trizen

Remove spaces at the beginning and end of your string. The fastest way, so far.

my $l = length($string); $string = reverse unpack("A$l",reverse unpack("A$l",$string));


Rate two-s/// split m-capture unpack s-with-\G two-s/// 239349/s -- -6% -38% -40% -41% split 255782/s 7% -- -33% -36% -37% m-capture 384362/s 61% 50% -- -4% -5% unpack 399865/s 67% 56% 4% -- -1%
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by Daddio

Similarly to infinityandbeyond, you could substitute out the leading and trailing white space like this.

$string =~ s/^\s*(.*?)\s*$/$1/;
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by The Mad Hatter

Regex::Common is also a good choice.

use Regexp::Common qw/whitespace/; $foo =~ s/$RE{ws}{crop}//g;
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by gridlock

You want to do a

s/^\s+//

followed by a

s/\s+$//
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by Bobinours

I read somewhere (probably in the CookBook) that it's faster to execute this :

$string=~s/^\s+//; $string=~s/\s+$//;
Than the one-liner :

$string =~ s/^\s+|\s+$//g;

Edited by davido: Removed useless use of /g modifier from the two-line (faster) example.
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by trizen

my $string = q{ this is a string }; $string = reverse unpack('A*',reverse(unpack 'A*',$string)); print "<$string>\n";
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by trizen

There are some faster solutions which sometimes can be really slow, depending on how many whitespaces a string contain.

If a string contains a lot of whitespaces.
Example: my $str = q{    }. q{a b c d e f g h i j} x 200 . q{    };

MRE book suggests this code:
$str =~ s/^\s+((?:.+\S)?)\s+$/$1/s;

I admit, I was surprised how fast it is compared with: "s/^\s+//" and his brother "s/\s+$//". They can't even compete at a benchmark, they are too slow with the above example! (that's because of the second regex which match at the end of the string, if fails so many times if string contains a lot of whitespaces (see re 'debug')).

Another approach (I know is silly, but is faster in some casses):

$str =~ s/^\s+//; $str = reverse($str); $str =~ s/^\s+//; $str = reverse($str);
Benchmark using the above example:
's_reverse' 42017/s -- -12% -48% 'unpack_A' 47847/s 14% -- -41% 'MRE_regx' 80645/s 92% 69% --
Answer: How do I remove whitespace at the beginning or end of my string?
contributed by Maestro_007

Try this, it's a little different, though it only works on leading whitespace:

s/\G //g
<paraphrase> It uses the \G anchor with the /g flag to start where the previous match left off, replacing spaces with nothing as it goes along. </paraphrase>

It's from p. 245 of Effective Perl Programming by Joseph N. Hall and Randal Schwartz (merlyn). Randal, if there's a problem with me quoting this stuff, just let me know.

Answer: How do I remove whitespace at the beginning or end of my string?
contributed by Mago

Remove whitespace at the beginning and end of your string, as well as consecutive whitespace (more than one whitespace character in a row) throughout the string.

$string = join(' ',split(' ',$string));

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others chanting in the Monastery: (11)
    As of 2014-10-23 05:25 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      For retirement, I am banking on:










      Results (124 votes), past polls