Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^2: Answer: How do I remove whitespace at the beginning or end of my string?

by choroba (Archbishop)
on Jan 30, 2012 at 09:04 UTC ( #950720=note: print w/replies, xml ) Need Help??


in reply to Re: Answer: How do I remove whitespace at the beginning or end of my string?
in thread regular expressions

Change it to
s/^\s+(\S?.*\S)\s+$/$1/s
  • Comment on Re^2: Answer: How do I remove whitespace at the beginning or end of my string?
  • Download Code

Replies are listed 'Best First'.
Re^3: Answer: How do I remove whitespace at the beginning or end of my string?
by repellent (Priest) on Jan 31, 2012 at 05:01 UTC
    use Test::More; sub trim { my $s = $_[0]; $s =~ s/^\s+(\S?.*\S)\s+$/$1/s; $s } is( trim(' '), '' ); is( trim('a '), 'a' ); is( trim(' a'), 'a' ); is( trim(' a '), 'a' ); is( trim('ab '), 'ab' ); is( trim(' ab'), 'ab' ); is( trim(' ab '), 'ab' ); is( trim('a bb c '), 'a bb c' ); is( trim(' a bb c'), 'a bb c' ); is( trim(' a bb c '), 'a bb c' ); done_testing(); __END__ not ok 1 # Failed test at ./t.pl line 12. # got: ' ' # expected: '' not ok 2 # Failed test at ./t.pl line 13. # got: 'a ' # expected: 'a' not ok 3 # Failed test at ./t.pl line 14. # got: ' a' # expected: 'a' ok 4 not ok 5 # Failed test at ./t.pl line 16. # got: 'ab ' # expected: 'ab' not ok 6 # Failed test at ./t.pl line 17. # got: ' ab' # expected: 'ab' ok 7 not ok 8 # Failed test at ./t.pl line 19. # got: 'a bb c ' # expected: 'a bb c' not ok 9 # Failed test at ./t.pl line 20. # got: ' a bb c' # expected: 'a bb c' ok 10 1..10 # Looks like you failed 7 tests of 10.

    The one I could find with best benchmark and passes tests is s/^\s*((?:.*\S)?)\s*$/$1/s;, which is essentially like MRE_regx with + replaced with * (perhaps trizen typo-ed?)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://950720]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2020-10-22 15:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (227 votes). Check out past polls.

    Notices?