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?
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;
}
You could use a look-behind assertion requiring at least one character:
s/(?<=.)[^ a-zA-Z0-9]/%/g;
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With