http://qs321.pair.com?node_id=241032


in reply to simple regex problem

All I want to do is swap any number of spaces (the first 2) with ":"

you want to replace the first two ocurrences of one or more spaces with ":"? and then replace any other more-than-one spaces (damn, my english sucks today!) with one space?

$line =~ s/\s+/ /g; # replace more than one space with one space $line =~ s/ /:/ for (1, 2); # replace the first two spcs with a colon #- does not work if there's only one space - $line =~ s/ (\S+) /:$1:/;
couldn't think of a way to do it with a single substitution...

update. fixed bug when there is only one space. thanks blakem!

hope it helps,

Replies are listed 'Best First'.
Re: Re: simple regex problem
by blakem (Monsignor) on Mar 07, 2003 at 00:27 UTC
    I like this approach (its the only one listed that fits the "only two" spec) but what happens if there is only one space?
    "this    hasonlyonespace" => "this hasonlyonespace"

    How about:

    $line =~ s/\s+/ /g; $line =~ s/ /:/ for (1,2);

    -Blake

Re: Re: simple regex problem
by Hofmator (Curate) on Mar 07, 2003 at 12:16 UTC
    $line =~ s/\s+/ /g;     # replace more than one space with one space

    This replaces a sequence of whitespaces with a single space char. This might or might not be what the poster wanted. To just affect spaces and replaces multiple occurrences with one, I'd recommend tr///: $line =~ tr/ / /s;

    -- Hofmator