Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

How do I write a regex for 'does not contain' a string.

by IraTarball (Monk)
on Aug 09, 2002 at 13:52 UTC ( [id://188907]=perlquestion: print w/replies, xml ) Need Help??

IraTarball has asked for the wisdom of the Perl Monks concerning the following question:

I've been regretably away from my mistress, Perl, for a while, and now I thougt I would whip out a short script to do some global text edits on a bunch of html files.

I was able to come up with something but it raised a question. Can you write a regex that matches all strings not containing the substring string 'foo'?

Here are my particular details...

I have a bunch of html files with blank images as spacers, but these don't always render right in mozilla unless they have a 'style="display:block"' attribute. Some designers were good about adding these and some were not, leading to fles whith a mix of haves and have not image tags. So what I thought was, "Find all the image tags that don't have a 'style="display:block"' attribute and add it. But how would you right that? I came up with:
#!/usr/bin/perl while(<DATA>) { if(m/<img\s+src="\/images\/blank.gif"/ && !m/display:block/) { print; s|(<img\s+src="/images/blank.gif".*?)>|$1 style="display:block +">|; print; } } __DATA__ <img src="/images/blank.gif" border="0"> <img src="/images/blank.gif" border="0" style="display:block" > <img src="/images/blank.gif" border="0">
this works, but it seems that I should be able to do this in a single s/// instead 2 matches and a swap. Thanks for taking the time to look at my post. I did a search for docs before posting but I could certainly have missed something. Pointers to pertinent nodes are appreciated.

Ira,

Replies are listed 'Best First'.
Re: How do I write a regex for 'does not contain' a string.
by Abigail-II (Bishop) on Aug 09, 2002 at 13:58 UTC
    /^(?:[^f]+|f(?!oo))*$/; # Matches strings not containing 'foo'. /^(?:(?!PATTERN).)*$/; # Matches strings not containing PATTERN +.
    The top one is reasonably fast, the bottom one is slow, but works for all patterns.

    Abigail

      Excelent! Thank you. I knew there must be a way to do this. Dispite the very valid points by fruiture and arturo about a better way to solve my particular problem, it was bugging me that I couldn't think of a way to do this.

      With much thanks,
      Ira

      "So... What do all these little arrows mean?"
      ~unknown

Re: How do I write a regex for 'does not contain' a string.
by arturo (Vicar) on Aug 09, 2002 at 15:14 UTC

    You're relying on a couple of things here, which may be OK and which may not be. If they are, disregard the code, which was written on the fly (but works with the sample input!). First, consider a line such as:

    <img src="blern.gif" /><span style="display:block" >foo!</span>

    That's going to pass your test. There's also that pesky problem that the tag need not all be on the same line:

    <img src="gern.jpg" border="0" style="display:block" />

    Pile on top of that the problem that it may already have a style element that doesn't contain the "display:block" and you're looking at trouble.

    So you could sanitize your input to make sure none of these is the case, but then you might as well make the whole thing more CSS-friendly (image spacers indeed! =). Actually, better than adding the inline style would be creating a class in your stylesheet that specifies display:block. But I'm getting ahead of myself, and probably of where you want to be.

    A more robust solution than any involving a hand-rolled regex would be to write a filter, presumably using HTML::Parser or a subclass thereof, that does the job, along the following lines:

    #!/usr/bin/perl # note, warnings are off because this shouldn't generate # 'em except where there is no "style" attribute on # image tags. use strict; use HTML::Parser; my $p=HTML::Parser->new( default_h => [ sub { print $_[0] }, 'text' ], start_h => [\&start_tag, 't +agname, attr, text']); $p->parse_file(*DATA); sub start_tag { my($tagname, $attr, $origtext) = @_; if ( ! ( $tagname eq "img") ) { print $origtext; return; } if ($attr->{style} !~/display:block/) { # avoid messy issues with other styles that may have been defined $attr->{style} = "display:block;". $attr->{style}; } print "<$tagname"; foreach ( keys %$attr) { print qq{ $_="} .$attr->{$_}.qq{"}; } print ">"; } __DATA__ <html> <head> <title>Boo</title> </head> <body bgcolor="#434343"> <h3>Hello</h3> <img src="witches.jpg"> <img src="macbeth.jpg" style="border: thick double #fcfcfc;"> <img src="foofaraw" style="width: 90"> <img src="cauldron.jpg" style="display:block"> <img src="fenny_snake.png"><span style="display: block">Hi there</sp +an> </body> </html>

    I mistrust all systematizers and avoid them. The will to a system shows a lack of integrity -- F. Nietzsche

      Thanks,
      As you and fruiture pointed out this is really what I want to use to solve my problem. I tweaked your code a bit to fit the real data and it's doing the job perfectly.

      Thanks again,
      Ira,

      "So... What do all these little arrows mean?"
      ~unknown

Re: How do I write a regex for 'does not contain' a string.
by fruiture (Curate) on Aug 09, 2002 at 14:25 UTC

    Well, I'd suggest you do not want to do what your question's title asks for (and what Abigail has already told you). You already can see it in your first attempts on solving your problem: you won't match img elements that have an attribute different from src in the beginning. You will miss elements, that have 'display:block' in their title-attribute. You will somehow produce duble style-attributes inmany cases...

    The solution is to use HTML::Parser or HTML::Tokeparser to fastly run through the text and extract img elements and explicitly check the style attribute for the display-property and add it if not present. That may be a bit slower in the end, but it will get all cases and produce good results.

    --
    http://fruiture.de

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://188907]
Approved by rob_au
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-12-09 23:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which IDE have you been most impressed by?













    Results (55 votes). Check out past polls.