Multiple substitutions with a single regular expression in perl

后端 未结 3 1091
心在旅途
心在旅途 2021-01-24 01:44

Say I have the following in perl:

my $string;
$string =~ s/ /\\\\ /g;
$string =~ s/\'/\\\\\'/g;
$string =~ s/`/\\\\`/g;

Can the above substitut

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-24 02:31

    $string =~ s/([ '`])/\\$1/g;
    

    Uses a character class [ '`] to match one of space, ' or ` and uses brackets () to remember the matched character. $1 is then used to include the remembered character in the replacement.

提交回复
热议问题