On 4/27/05, Ramprasad A Padmanabhan wrote:
> Hi all,
> 
>   I want a regex to replace all continuous occurrences of '-' with
> something else say 'x' except the first one
> 

Here's one way:
   s/-(-+)/"-".("x"x length$1)/ge;

Explanation:
Flags: "g" means global, i.e. replace all occurences, and "e" means to
eval the replacement part as a perl expression and use the return
value as the replacement. Read "perldoc perlop", the section on the
s/// operator, for mode details.
First part: "-(-+)" means to match a "-" sign followed by one or more
"-" signs, and save the "-" signs except for the first into $1. Note
that this means that single "-" signs will not be matches and
therefore affected at all.
Second part: returns a "-" (instead of the first, unsaved "-" we
matched in part one), concatanated (that's the ".") with the char "x"
repeated length of $1 times (see "perldoc perlop", section on
"Multiplicative Operators" for explanation of the x op, see "perldoc
-f length" for an explanation of the length function.

Some example code:
################## begin code
use strict;
use warnings;
while (<DATA>) {
   chomp(my $orig = $_);
   s/-(-+)/"-".("x"x length$1)/ge;
   print "$orig   ====>   $_";
}
__DATA__
bla
- Ram
-- bla
bla ---
-- blah ---
################## end code
 
HTH,
-- 
Offer Kaye

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to