Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

string substitution

by Gosh (Initiate)
on Dec 04, 2010 at 10:31 UTC ( #875352=perlquestion: print w/replies, xml ) Need Help??
Gosh has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks!
I want to delete all the 'spaces' between non "word" characters:
my $line = "& & &"; $line =~ s/(\W)\s+(\W)/$1$2/g; print $line;
The program outputs "&& &" but I expect "&&&"
Could You explain me why output is "&& &" but not "&&&"? Could You help me how to reach my goal? Thanks!

Replies are listed 'Best First'.
Re: string substitution
by Corion (Pope) on Dec 04, 2010 at 10:35 UTC

    Whitespace is contained in [^\w]. Maybe you want to use \S instead of [^\w]? Or, if you just want to remove all spaces, why don't you use s/\s//g?

      Thanks for answer. This regexp does the thing: s/(\W)\s+/$1/g

        That's probably not doing what you want, at least according the your original problem specification which called for removing spaces between, rather than after, characters. Consider:

        use strict; use warnings; my $str = "The quick & the dead."; $str =~ s/(\W)\s+/$1/g; print $str;


        The quick &the dead.
        True laziness is hard work
Re: string substitution
by AnomalousMonk (Canon) on Dec 04, 2010 at 12:17 UTC
    ... why output is "&& &" but not "&&&"?

    After the first match on  '& &' (which is replaced with '&&'), the 'match point' in the string is sitting just after the second '&' and just before the second space. The regex pattern needs at least three characters to match, and at that point there remain only two characters in the string.

    In general, the regex of the OP will only match successive triplets of  '& &' leaving a single  \s between each substituted  '&&' pair because after each match the regex engine must scan forward to find, at the very least, another  \W\s\W triplet. (Heed Corion's caution that  \W includes all  \s characters!)

Re: string substitution
by BrowserUk (Pope) on Dec 04, 2010 at 10:46 UTC

    Like this?

    $s = 'a b & & * * * * a * * * *& && & xy a';; $s =~ s[(?<=\W)\s+(?=\W)][]g;; print $s;; a b &&**** a ****&&&& xy a

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://875352]
Approved by pKai
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2017-04-23 17:12 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (431 votes). Check out past polls.