Perl:正则表达式 - 无法识别的转义符已通过

时间:2018-03-16 07:00:04

标签: regex perl

我有以下代码:

use strict;
use warnings;

my $find = "(.*\s+)(subject:)(.*)(_1)(\s+.*)";
my $replace = '"\nsubject: \t\t$3_2"';

my $var_1 = "Time: 1000-1200    subject:    Physic_1    Class: Room A";
my $var_2 = "Time: 1000-1200    subject:    Math_1  Class: Room A";
$var_1 =~ s/$find/$replace/ee;
$var_2 =~ s/$find/$replace/ee;
print $var_1."\n";
print $var_2."\n";

我希望输出只提取主题并将_1更改为_2,如:

Output:
subject:      Physic_2
subject:      Math_2

然而,我得到的是:

Output:
Unrecognized escape \s passed through at test.pl line 20.
Unrecognized escape \s passed through at test.pl line 20.
Time: 1000-1200 subject:        Physic_1        Class: Room A
Time: 1000-1200 subject:        Math_1  Class: Room A

如何将字符串变量中的\ t,\ s +,\ n转义为perl正则表达式模式?

更新: 如果我做这样的事情:

my $pattern = 's/(.*\s+)(subject:)(.*)(_1)(\s+.*)/\nsubject: \t\t$3_2/g';
my $var = "Time: 1000-1200   subject:    Physic_1    Class: Room A";
$var =~ $pattern;
print $var."\n";

它给出了输出,似乎没什么变化:

Time: 1000-1200   subject:    Physic_1    Class: Room A

2 个答案:

答案 0 :(得分:3)

双引号内插反斜杠字符。 \s在正则表达式中具有特殊含义,但不是双引号 - 因此警告。改为使用单引号。

my $find = '(.*\s+)(subject:)(.*)(_1)(\s+.*)';

或者,如果出于某些其他原因需要双引号,请将正则表达式中应该存在的反斜杠加倍:

my $find = "(.*\\s+)(subject:)(.*)(_1)(\\s+.*)";

答案 1 :(得分:0)

您可以在第一行完全按照第二行中的操作执行此操作:

my $find = '(.*\s+)(subject:)(.*)(_1)(\s+.*)';

输出:

subject:                    Physic_2

subject:                    Math_2