Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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 making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2020-02-21 13:05 GMT
Find Nodes?
    Voting Booth?
    What numbers are you going to focus on primarily in 2020?

    Results (95 votes). Check out past polls.