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

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

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

However, I do not know how to change this expression to replace all the required special EXCEPT characters for the first in the line. Therefore, if my line looks like

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

it will be

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

(The first "&" is also being replaced right now).

Can anyone help?

+6
source share
3 answers

This changes everything except the first instance of the match target by a percent symbol:

 { my $count = 0; $string =~ s{([^ a-zA-Z0-9])}{$count++ ? "%" : $1}ge; } 
+3
source

You can use the look-behind statement that requires at least one character:

 s/(?<=.)[^ a-zA-Z0-9]/%/g; 
+3
source
 substr($string, 1) =~ s/[^ a-zA-Z0-9]/%/g; 

Refresh . The above only works if the special character is the first character of the string. The following works are independent of where they are 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); 
+2
source

Source: https://habr.com/ru/post/886387/


All Articles