This is fairly verbose but I like to use HTML::Parser for parsing non-standard tagged text as it is very flexible and can be fine-tuned. Also good as a learning exercise.
use HTML::Parser; use Data::Dumper; my $tag_string = 'word1 <tag0> word2 <tag1>word3 word4</tag1> word5 </ +tag0> word6 <tag2>word7 word8</tag2> word9 <tag3>word10</tag3> word11 +'; my $tags = parse_string( $tag_string ); print Dumper( $tags ); sub parse_string { my $string = shift; my %tags; my %check_tags; my $in_tag = 0; my $current_tag = 'no_tag'; my $prev_tag; # process start tag event my $start = sub { my ($tag) = @_; $check_tags{$tag}++; $in_tag++; $prev_tag = $current_tag; $current_tag = $tag; }; # process text event my $text = sub { my ($text) = @_; $text =~ s/^\s+//; $text =~ s/\s+$//; return if not length $text; my @words = split(m/\s+/, $text); push( @{ $tags{$current_tag} }, @words); }; # process end tag event my $end = sub { my ($tag) = @_; $check_tags{$tag}++; $in_tag--; $current_tag = $in_tag ? $prev_tag : 'no_tag'; }; my $parser = HTML::Parser->new( api_version => 3, start_h => [$start, "tagname"], text_h => [$text, "text"], end_h => [$end, "tagname"], default_h => [$text, "text"], ); $parser->parse($string); $parser->eof; # check each tag has an end tag for my $tag (keys %check_tags) { if ($check_tags{$tag} % 2) { print "<$tag> is not valid\n"; } } return \%tags; }
Output:
$VAR1 = { 'no_tag' => [ 'word1', 'word6', 'word9', 'word11' ], 'tag0' => [ 'word2', 'word5' ], 'tag1' => [ 'word3', 'word4' ], 'tag2' => [ 'word7', 'word8' ], 'tag3' => [ 'word10' ] };

In reply to Re: Parsing string with tags by tangent
in thread Parsing string with tags by Dirk80

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.