[英]How to match the first line and store regex match in the subsequent lines in perl?
我有一个头文件,我想在perl中使用regex提取一些变量。
以下是头文件的一部分:
banana.h
/******************************************************************************/
// BANANA = 1,
/******************************************************************************/
#define BANANA_FAMILY_GREEN 0x01
#define BANANA_FAMILY_YELLOW 0x02
#define BANANA_FAMILY_SPECIAL 0x03
#define BANANA_MAJOR_VER_SWEET 0x01
#define BANANA_MAJOR_VER_BITTER 0x02
#define BANANA_MINOR_VER_BIG 0x01
#define BANANA_MINOR_VER_SMALL 0x02
/******************************************************************************/
// POTATO = 2,
/******************************************************************************/
.
.
.
假设我要匹配“ BANANA = 1”,还要匹配“ / ************************************** ************ /“可以使用模式” #define“找到其下方的模式,并提取” BANANA_FAMLY_GREEN 0x01“,依此类推。
以下是我正在使用的正则表达式模式:
if ($banana_header =~ m/.*\s*BANANA\s*\=\s*\d+\s*.+/)
{
next;
if ($banana_header =~ m/#define\s*(\w+)\s*0x(\d+)\s*/)
{
print "word:$1\n";
print "digit:$2\n";
}
}
但是我似乎无法进入第二种if条件的方法,在这里我缺少什么吗? 我试过使用修饰符/ s并将换行符与匹配。 但这似乎也不起作用。
正如@choroba提到的那样next;
使其余部分无法访问。 除此之外,第二个if语句也不会到达,因为下一轮将包含下一行,因此打印匹配的代码仍然不会到达。 我不确定您是如何填充$ banana_header的,但是假设您正在从STDIN读取,则该方法应该有效:
$fruit_flag=0;
while(<STDIN>)
{
chomp;
$banana_header=$_;
if ($fruit_flag == 0 && $banana_header =~ m/.*\s*BANANA\s*\=\s*\d+\s*.+/)
{
$fruit_flag=1;
next;
}
if ($fruit_flag)
{
if ($banana_header =~ m/#define\s*(\w+)\s*0x(\d+)\s*/)
{
print "word:$1\n";
print "digit:$2\n";
}
elsif ($banana_header =~ m/\/\//)
{
$fruit_flag=0;
}
}
}
尝试这样做:
BEGIN { $/ = "\000"; $\ = undef; }
while (defined($_ = <ARGV>)) {
print $1, $2 if /\b(BANANA\s*\=\s*\d+),\s*\n.*\n#define(.*)/;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.