Re: match nested tags
- From: "Xicheng Jia" <xicheng@xxxxxxxxx>
- Date: 30 Apr 2006 05:38:37 -0700
FangQ wrote:
hi
is there a simple way using regular expression to find nested tags?
for example, the string is:
{{ {A} this is part A of the document
{{ {A.1} this is part A1 }}
}}
I want to define a function findtag("A") to give me
this is part A of the document
{{ {A.1} this is part A1 }}
and findtag("A.1") to give me
this is part A1
can anyone give some hint?
Here is a general solution for capturing nested constructs from
Jeffery's book "Mastering Regular Expressions" 2nd edition. it counts
the number of opening/closing constructors and return contents between
two balanced constructors.
____________________________________________
use strict;
use warnings;
my $str=<<'END_TEST';
{{ {A} this is part A of the document
{{ {A.1} this is part A1 }}
}} ABCDEFGUI {{ {A} this is part A2 of the document
{{ {A.2} this is part A2 }}
}}
END_TEST
my @x = findtag($str, "A");
print join "\n=new=\n", @x;
#######################
sub findtag {
my ($string, $tag) = @_;
use re 'eval';
my $opening = qr/\{\{/;
my $closing = qr/}}/;
my $normal = qr/(?!$opening|$closing)./s;
my $nested = qr/
(?{ local $n = 0 })
(?>
(?:
$normal+
| $opening (?{ $n++ })
| $closing (?(?{ $n != 0 }) (?{ $n-- }) | (?!) )
)*
)
(?(?{ $n != 0 })(?!))
/x;
my @contents;
push @contents, $1
while $string =~ /$opening\s*\{$tag}\s*($nested)\s*$closing/go;
return wantarray ? @contents : $contents[0];
}
__________________________
Xicheng
.
- References:
- match nested tags
- From: FangQ
- match nested tags
- Prev by Date: Re: 'Tie::StdScalar' - perl tells me it can't find it
- Next by Date: Anyone interested: please comment on this code
- Previous by thread: match nested tags
- Next by thread: Anyone interested: please comment on this code
- Index(es):
Relevant Pages
|