in reply to A nice text processing question
My solution will probably make you rethink that...
I'd use a regex lookahead to catch and strip paired HTML tags such as bolding (<b>blah</b>) or italics(<i>blah</i>). However, note that my snippet breaks on the final line of DATA, because the lookahead in the regex assumes that the closing HTML tag will just be </$1>
Update: Tweaks to make above script handle unpaired open/close tags, such as#!/usr/bin/perl use strict; use warnings; while(<DATA>) { chomp; while ( m{ <([^>]*?)> [^<]*? </\1> }gx ) { my $token = $1; s{<$token>}{}g; s{</$token>}{}g; } # Of course, this will be hard to do if you # "don't know how many dashes, if any, will # be there." print "\t$_\n" for ( split (/-- /,$_) ); print "\n"; } __DATA__ This is a -- string of -- words <b>This is a -- string of -- words</b> This <b>is a -- string</b> of -- words This <i>is</i> a -- <b>string</b> of -- words This <i>is a -- <b>nested set</b> of</i> -- tokens This is -- a nifty -- <A HREF="http://google.com">search engine</A>
This can't handle paired and unpaired tags in the same line (see last line of data, which causes script to hang, hence the # and the skip condition)
Urgh. HTML::Parser really is your friend here. btw I wanted to comment my regexes but found myself unable to adequately describe them.#!/usr/bin/perl use strict; use warnings; while(<DATA>) { /^#/ and next; chomp; if ( m{ <([^>]*?)> [^<]*? </\1> }x ) { while ( m{ <([^>]*?)> [^<]*? </\1> }gx ) { my $token = $1; # Some verbose info. Note first line doesn't # get printed because it doesn't match regex print $_, "\n"; print "Found <$token> and </$token>, removing...\n"; s{<$token>}{}g; s{</$token>}{}g; } } else { # <A HREF="http://google.com">search engine</A> while ( m{ </([^>]*?)> }x ) { my $close = $1; if ( m{ <($close[^>]*?)> [^<]*? </$close> }x ) { my $open = $1; print $_,"\n"; print "Found <$open> and </$close>, removing\n"; s{<$open>}{}g; s{</$close>}{}g; print $_,"\n"; } } } # Of course, this will be hard to do if you # "don't know how many dashes, if any, will # be there." print "\t$_\n" for ( split (/-- /,$_) ); print "\n"; } __DATA__ This is a -- string of -- words <b>This is a -- string of -- words</b> This <b>is a -- string</b> of -- words This <i>is</i> a -- <b>string</b> of -- words This <i>is a -- <b>nested set</b> of</i> -- tokens This is -- an awesome -- <A HREF="http://google.com">search engine</A> Truly an -- ugly -- <A HREF="http://perl.com"><FONT COLOR="RED">nested +</FONT> st ring</A> #This string -- <b>causes -- <A HREF="http://perl.com"><FONT COLOR="RE +D">my box</ b></FONT> to hang</A>
blyman
setenv EXINIT 'set noai ts=2'
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: A nice text processing question
by moseley (Acolyte) on Jan 05, 2002 at 20:05 UTC | |
by belden (Friar) on Jan 06, 2002 at 00:25 UTC | |
|
Re: Re: A nice text processing question
by dragonchild (Archbishop) on Jan 07, 2002 at 19:22 UTC |