in reply to stripping characters from a string

if you're trying to normalize a string so you can make a decent filename out of it- which i get the feeling here (slap me if i'm wrong..)

my $fus=qq|This Is some Funkah Lookin' & Zmellin' "straeyang"|; $fus=~s/\W/_/g; # now $fus equals This_Is_some_Funkah_Lookin____Zmellin_ __straeyang_ #great. super. let's clean that up $fus=~s/_+/_/g; # now $fup equals This_Is_some_Funkah_Lookin_Zmellin_straeyang_ #let's get rid of any _ in ends $fus=~s/^_+|_+$//g; print $fus; # prints This_Is_some_Funkah_Lookin_Zmellin_straeyang #maybe im tight and i don't want any uppercase $fus = lc($fus); #now $fus = this_is_some_funkah_lookin_zmellin_straeyang #anyway.. you get the idea

Maybe you want to get rid of funny chars? like non word chars? then use \W, that means *any* non word characters, as opposed to (\w which are 0-9, a-z, A-Z, _ anyway..)

Replies are listed 'Best First'.
Re^2: stripping characters from a string
by radiantmatrix (Parson) on Mar 06, 2006 at 19:35 UTC

    Good post. Here's what I would do if all I wanted was your last result:

    # note the lower-casing inline ($fus = lc $fus) =~ s/\W+/_/g; #all spans of 1 or more non-words becom +e 1 '_' $fus =~ s/^_|_$//g; #at most one on each end, because of th +e above

    But, for the poster's question, removing all single-quotes and migrating spaces to _...

    for ($string) { s/\s+/_/g; #convert 1+ spaces to a single '_' s/'|^_|_$//g; #trim lead/trail _ and remove single quotes }

    Which is going a bit further than the direct solution of

    $string =~ tr/\s'/_/d;
    <-radiant.matrix->
    A collection of thoughts and links from the minds of geeks
    The Code that can be seen is not the true Code
    I haven't found a problem yet that can't be solved by a well-placed trebuchet