【发布时间】:2011-11-04 15:24:35
【问题描述】:
我是 Perl 的初学者。有人可以帮助我如何从下面的脚本中正确提取数据吗?
#####################################################################
#! /usr/bin/perl
$text = "Name: Anne Lorrence Name: Burkart Name: Claire Name: Dan" ;
$match = 0 ;
while ($text =~ /Name: \b(\S+)\s+(\S+)\b/g || /Name: \b(\S+)\b/g) {
++ $match ;
print "Match number $match is $1 $2\n" ;
}
######################################################################
我希望我的输出是这样的:
Match number 1 is Anne MLorrence
Match number 2 is Burkart
Match number 3 is Claire
Match number 4 is Dan
但事实上,我的脚本给了我这个:
Match number 1 is Anne MLorrence
Match number 2 is Burkart Name
我可以知道出了什么问题吗?
【问题讨论】:
-
“Anne MLorrence”中的“M”应该来自哪里,输入“Anne Lorrence”?
/Name: \b(\S+)\b/g匹配的是什么? (提示:$_,而不是$text)。 -
我会简单地
split("/Name:\s+/)并丢弃第一个匹配项。使用两个单独的正则表达式和if (/r1/g|| /r2/g)在任何情况下都不起作用,因为/g匹配指针不会保持同步。不过,您可以将其按摩成一个正则表达式。提示:使用非贪婪匹配或否定前瞻断言。
标签: perl