Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trim whitespaces > beginning and end 1

Status
Not open for further replies.

Extension

Programmer
Nov 3, 2004
311
CA

Hi

I'm trying to get rid of the whitespaces at the beginnning and at the end of a string.
Chomp does trim the trailing spaces, but that's it.

So the following string " this is a string " would become "this is a string
 

I'm using these regex's right now:
Can they be combined or simplified ?

Code:
$Chars =~ s/^\s+//;
$Chars =~ s/\s+$//;
 
Code:
s/^\s*(.*?)\s*$/$1/;

also empties strings only containing white space (just in case this makes any difference).

Holger
 
the way you are doing it looks to be the best, it will most likely be faster than the other suggestions. Sometimes two regexps are better than one!
 
I'm not sure I agree with you Kevin.
With two regexs your have two compilations and that probably takes much longer than executing the regex.
If anyone fancies testing them I'd be interested to see which is actually faster.


Trojan.
 
Looks as if Kevin is totally right:

Code:
#!/usr/bin/perl -w
use strict;

my @strings = ("  foo   ", "    bar    ", "   foo bar   ");

for (1..100000) {
  foreach my $string (@strings) {
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
  }
}

results in

real 0m1.021s
user 0m1.000s
sys 0m0.000s

whereas Trojans solution results in

real 0m4.067s
user 0m4.030s
sys 0m0.000s

and finally mine in

real 0m4.653s
user 0m4.610s
sys 0m0.000s

 
O'Reilly's Mastering Regular Expressions recommends the two regex solution because, as pointed out, its faster.
 
Yep, we noticed that!
I think it's also more readable.
A star for Kevin for being smarter than the rest of us!
(you know you can go off people!) ;-)


Trojan.
 
Thanks to all for the help.

regex7
Thank you for your input and for the stats.

Kevin & Trojan
As usual, thank you very much for your help. It's always appreciated to get your advice.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top