http://www.perlmonks.org?node_id=1077853


in reply to *fixed*Problem with <> and regex

Hi luxlunae, The "<*" part of your regex means "match any number of less-than (<), including zero". So the whole thing will get rid of any number of "<" immediately followed by a single ">".

Closer (though still not correct) is:

$words =~ s/<.*>//g;

which means "get rid of "<" and ">" and anything between. The reason it's still not correct is because it will delete multiple <...> ... <...> from the line, including the text within it. (try it and see). That is to say, it matches (and deletes) this entire line:

<span class="author-name" itemprop="author">Romaxton</span>

A real solution would be:

$words =~ s/<[^>]+>//g;

where the "[^>]+" part means "1 or more of any character except greater-than ">". That regex should therefore get rid of all occurrences of <...> in the line, without removing non-tag text in between.

Edit: it's worth pointing out another solution would be to use the "non-greedy" quantifier "?" in "still not correct" example I gave above:

$words =~ s/<.*?>//g;

which would have the effect of matching the shortest possible "<...>" each time, and thus avoid getting multiple pairs.

Edit 2: fixed misspelling of "$word" to "$words".

say  substr+lc crypt(qw $i3 SI$),4,5

Replies are listed 'Best First'.
Re^2: Problem with <> and regex
by luxlunae (Novice) on Mar 11, 2014 at 15:20 UTC
    The first solution did indeed delete my entire line, but the second option just crashes the script :(. This is what fails:
    sub clean { my ($words) = @_; print "WordsBefore: $words \n"; $word =~ s/<[^>]+>//g; print "WordsAfter: $words \n"; return $words; }
      How exactly is it "crashing your script"? Is it providing any error message? Any output?

      Edit:   I just noticed that you're passing "$words", but then operating on "$word", which is probably your error. Granted you probably cut and paste what I wrote (so the error is actually mine -- sorry!). Change "$word" to "$words".

      You should also have:

      use strict; use warnings;
      at the top of your script (maybe you do, and that's why your script was failing). If not, add them; they'll tell you what you're doing wrong in exactly this type of situation.
      say  substr+lc crypt(qw $i3 SI$),4,5