如何使用perl从文本中获取所需的字符串

时间:2013-09-24 11:43:48

标签: perl

以下是要修剪的文字:

/home/netgear/Desktop/WGET-1.13/wget-1.13/src/cmpt.c:388,error,resourceLeak,Resource leak: fr

从上面的文字我需要获取“:”旁边的数据。我如何获得388,error,resourceLeak,Resource leak: fr

2 个答案:

答案 0 :(得分:3)

您可以使用split根据分隔符将字符串分隔为列表。在您的情况下,分隔符应为:

my @parts = split ':', $text;

由于要提取的文本也可以包含:,请使用limit参数在第一个之后停止:

my @parts = split ':', $text, 2;
然后

$parts[1]将包含您要提取的文本。您也可以将结果传递到列表中,丢弃第一个元素:

my (undef, $extract) = split ':', $text, 2;

答案 1 :(得分:1)

除了@RobEarl's建议使用split之外,您还可以使用正则表达式来执行此操作。

my ($match) = $text =~ /^[^:]+:(.*?)$/;

正则表达式:

^          the beginning of the string
[^:]+      any character except: ':' (1 or more times)
    :      match ':'
(          group and capture to \1:
 .*?       any character except \n (0 or more times)
)          end of \1
$          before an optional \n, and the end of the string

$match现在将保留捕获组#1的结果..

388,error,resourceLeak,Resource leak: fr