jeanluca has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I've a problem with a string I need to parse. Here are a few examples of this string:
$str = " abc defgh ij klmnop " ; # case 1 $str = " abc defgh ij klmnop qrst uvwxyz" ; # case 2 $str = "abc defgh ij" ; #case 3
I need the text + the spaces in between but not the spaces at the beginning or end!!
I tried to find a regexp for this, this one almost works:
($str) = ($str =~ /^\s([\w+\s{0,}]{1,})\s{0,}$/) ; #case 2/3
It only fails in case 1, it leaves a space at the end....
Any suggestions how to fix this expression ?

Thanks in advance
Luca

Replies are listed 'Best First'.
Re: regexp problem
by Limbic~Region (Chancellor) on Dec 08, 2005 at 13:38 UTC
    jeanluca,
    Perhaps I am being dense but it sounds like what you want to do is remove leading and trailing whitespaces. This is a FAQ IIRC. In any case - the following should do the trick:
    $str =~ s/^\s+|\s+$//g;

    Cheers - L~R

Re: regexp problem
by secret (Beadle) on Dec 08, 2005 at 13:36 UTC
    maybe you can trim the spaces at the ends first ?
    s/^\s+//, s/\s+$// for $string;
Re: regexp problem
by ysth (Canon) on Dec 08, 2005 at 13:39 UTC
    ($str) = ($str =~ /^\s*(.*?)\s*\z/) or just
    $str =~ s/^\s+//; $str =~ s/\s+\z//;
Re: regexp problem
by SamCG (Hermit) on Dec 08, 2005 at 15:29 UTC
    from perlfaq:
    for ($string) { s/^\s+//; s/\s+$//; }
Re: regexp problem
by Perl Mouse (Chaplain) on Dec 08, 2005 at 14:12 UTC
    If you may assume the string contains at least two non-space characters, I'd write:
    /(\S.*\S)/
    which will match the first non-space character, the last non-space character, and everything in between. If you may not make the assumption, I'd modify it slightly:
    /(?=\S)(.*\S)/
    If you know the non-space characters will be letters (or digits or underscores), you can also write:
    /(\b.+\b)/
    which also works for strings containing just a single letter.
    Perl --((8:>*