2016-11-16 34 views
-1

我输入的时候替换和删除:在Perl的正则表达式相同取一些字符串

$str = 'In order to study the opportunity cost of allocating time to the less beneficial act, we need appropriate schedules of reinforcement description <?processing-instruction \value{[email protected]@%}?> list we need appropriate schedules of reinforcement'; 

my $get_val = ($str=~m/<\?processing\-instruction\s*\\value\{([^\}\?>]*)\}\?>/gi)[0]; 

print $get_val; 

不过,我需要删除整个处理指令标签的同时寻找相同。这是否可能在相同的模式?

我试过这个,但没有成功。

my ($get_val) = ($str=~s/<\?processing\-instruction\s*\\value\{([^\}\?>]*)\}\?>//gi)[0]; 

print $get_val; 

上面的输出打印'1'。如果有人能帮助解决这个问题,我们将不胜感激。

在此先感谢。

+0

它打印$$ @@%'我。你确定你发布了你正在运行的确切代码吗? – toolic

+0

@toolic:虽然匹配这个是成功的,但是当替换它时不会打印。 – ssr1012

+1

perl中的替换运算符返回替换次数,与匹配运算符不同,后者返回已加工和收集的元素列表。 –

回答

2

如果替换成功,则您想要的值将在$1中。

#!/usr/bin/perl 

use strict; 
use warnings; 
use 5.010; 

my $str = 'In order to study the opportunity cost of allocating time to the less beneficial act, we need appropriate schedules of reinforcement description <?processing-instruction \value{[email protected]@%}?> list we need appropriate schedules of reinforcement'; 

if ($str =~ s/<\?processing\-instruction\s*\\value\{([^\}\?>]*)\}\?>//gi) { 
    say $1; 
} 

say $str; 

输出:

[email protected]@% 
In order to study the opportunity cost of allocating time to the less beneficial act, we need appropriate schedules of reinforcement description list we need appropriate schedules of reinforcement 
+0

是的。我需要在代码中学习这种逻辑和思维方式。真棒。 – ssr1012

2

试试这个:

<\?processing-instruction.*?\?> 

由空字符串替换

Explanation

Perl代码示例:

use strict; 

my $str = 'In order to study the opportunity cost of allocating time to the less beneficial act, we need appropriate schedules of reinforcement description <?processing-instruction \\value{[email protected]@%}?> list we need appropriate schedules of reinforcement'; 
my $regex = qr/<\?processing-instruction.*?\?>/p; 
my $subst = ''; 

my $result = $str =~ s/$regex/$subst/rg; 

print $result; 

Run the code here

+0

非常感谢 – ssr1012

相关问题