Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl regular expression: how to replace all desired character except of the first one

Tags:

perl

I have a regular expression that replaces all special characters with % (for database searching with LIKE). It looks like this:

$string =~ s/[^ a-zA-Z0-9]/%/g;

However I don't know how to change that expression to replace all desired special characters EXCEPT for the first one in a string. So if my string look like

"&Hi I'm smart(yeah right...)"

it would be

"&Hi I%m smart%yeah right%%%%"

(Right now the first '&' is also replaced).

Can any one help?

like image 865
srd.pl Avatar asked Apr 21 '11 11:04

srd.pl


3 Answers

This changes all but the first instance of the match target into a percent symbol:

{
    my $count = 0;
    $string =~ s{([^ a-zA-Z0-9])}{$count++ ? "%" : $1}ge;
}
like image 110
tchrist Avatar answered Oct 18 '22 13:10

tchrist


You could use a look-behind assertion requiring at least one character:

s/(?<=.)[^ a-zA-Z0-9]/%/g;
like image 31
FMc Avatar answered Oct 18 '22 12:10

FMc


substr($string, 1) =~ s/[^ a-zA-Z0-9]/%/g;

Update: The above only works if the special character is the first character of the string. The following works no matter where it's located:

my $re = qr/[^ a-zA-Z0-9]/;
my @parts = split(/($re)/, $string, 2);
$parts[2] =~ s/$re/%/g if @parts == 3;
$string = join('', @parts);
like image 41
ikegami Avatar answered Oct 18 '22 14:10

ikegami