Home > Archive > PERL Beginners > August 2007 > Regex Issue
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
|
|
| Dharshana Eswaran 2007-08-29, 4:00 am |
| Hi All,
I have written a program,
use strict;
use warnings;
my $Enum = "typedef enum _SIGNAL_E
{
LEVEL_0_EV = 0,
LEVEL_1_EV,
LEVEL_2_EV,
LEVEL_3_EV,
LEVEL_4_EV,
LEVEL_5_EV
} SIGNAL_E;";
my $Enumidentifier = qr{ [A-Z0-9_]\w* }xs;
my $Enumstatement = qr{
\s*
($Enumidentifier)
\s*
=?
\s*
(\S+)?
,?
}xs;
my @m = $Enum =~ /$Enumstatement/g;
my $len = @m;
for(my $i =0; $i<$len; $i++) {
print "$m[$i]\n";
}
The output for this program is
_SIGNAL_E
{
LEVEL_0_EV
0,
LEVEL_1_EV
,
LEVEL_2_EV
,
LEVEL_3_EV
,
LEVEL_4_EV
,
LEVEL_5_EV
}
SIGNAL_E
;
But i want to read only the elements of the Enum and the values assigned to
those elements. I dont want to read the Enum names and the extra characters.
I am unable to filter them.
The desired output is
LEVEL_0_EV
0
LEVEL_1_EV
LEVEL_2_EV
LEVEL_3_EV
LEVEL_4_EV
LEVEL_5_EV
Can anyone help me in correcting the regex?
Thanks and Regards,
Dharshana
| |
| Chas Owens 2007-08-29, 7:59 am |
| On 8/29/07, Dharshana Eswaran <dharshana.ve@gmail.com> wrote:
snip
> But i want to read only the elements of the Enum and the values assigned to
> those elements. I dont want to read the Enum names and the extra characters.
> I am unable to filter them.
snip
Sometimes one regex is not enough. The following code has at least
one bug: it doesn't correctly handle enums of characters where one of
the characters is ',' (a valid C construct, but on I don't see often).
#!/usr/bin/perl
use strict;
use warnings;
my $text = "typedef enum foo {
LEV_0 = 0,
LEV_1,
LEV_2,
LEV_3,
LEV_4,
LEV_5
} sig;
typedef enum bar {
LEV_0 = 1,
LEV_1 = 2,
LEV_2=4,
LEV_3 = 8,
LEV_4 =16,
LEV_5 =32
} flag;";
my $ident = qr/ [A-Za-z_]\w+ /xs;
my $typedef = qr/ typedef \s+ /xs;
my $enum = qr/ $ident (?: \s* = \s* [^\s,]+)? /xs;
my $enum_statement = qr/
$typedef?
enum
\s+
($ident)
\s*
{
\s*
((?: $enum \s* ,? \s* )+)
\s*
}
/xs;
while ($text =~ /$enum_statement/g) {
my ($name, $block) = ($1, $2);
print "$name\n";
for my $e ($block =~ /($enum)/g) {
$e =~ s/\s*=\s*/ has a value of /;
print "\t$e\n";
}
}
|
|
|
|
|