2016-11-16 56 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

相關問題