Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: simple regex problem

by CukiMnstr (Deacon)
on Mar 06, 2003 at 23:13 UTC ( #241032=note: print w/replies, xml ) Need Help??

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);


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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2020-10-30 23:13 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (286 votes). Check out past polls.