使用Perl正则表达式替换星号(*)

0 regex perl

我有以下字符串:

$_='364*84252';

问题是:如何*用其他东西替换字符串?我试过了s/\*/$i/,但是有一个错误: Quantifier follows nothing in regex.另一方面s/'*'/$i/,不会导致任何错误,但它似乎也没有任何影响.

Vin*_*vic 8

别的东西在这里很奇怪......

~> cat test.pl
$a = "234*343";
$i = "FOO";

$a =~ s/\*/$i/;
print $a;

~> perl test.pl
234FOO343
Run Code Online (Sandbox Code Playgroud)

找到的东西:

~> cat test.pl
$a = "234*343";
$i = "*4";

$a =~ m/$i/;
print $a;

~> perl test.pl
Quantifier follows nothing in regex; marked by <-- HERE in m/* <-- HERE 4/ at test.pl line 4.
Run Code Online (Sandbox Code Playgroud)

解决方案,使用\Q和转义变量中的特殊字符\E,例如(TIMTOWTDI)

~> cat test.pl
$a = "234*343";
$i = "*4";

$a =~ m/\Q$i\E/;
print $a;

~> perl test.pl
234*343
Run Code Online (Sandbox Code Playgroud)