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

Hello brethren, I'm work on a regexp that will match a background-color style attribute. Here's what i've come up with so far: /(background)-(color):\s*#(.{6});*/ I'm focusing on hexdecimal volor values, hense the '#'. The regexp checks out on the test program i've put together, though I'm wondering if there is a better approach that simply search for 6 characters of any type? A combo of word and digit metacharacters? Cheers

Replies are listed 'Best First'.
Re: Background color HTML regexp
by ViceRaid (Chaplain) on Aug 22, 2003 at 15:34 UTC

    Three little things, beyond what's said above: you might want to look at CPAN modules for dealing for CSS. They'll parse a bit of CSS for you and then let you get hold of the background-color attributes using a hash. Too easy!

    You probably don't need the brackets round "background" and "color" in your regexp. The brackets will make perl remember what it found inside those brackets and store it in the $1 and $2 variables. That's probably a bit wasteful unless you need it.

    Finally, it's valid CSS to have 3 characters rather than 6 specifying a hex colour value. See colour units in the CSS spec. Also, CSS is (mostly) case insensitive, so you probably want to match BACKgrouNd-CoLoR as well. Well, here's a slightly modified version:

    if ( $css =~ /background-color\s*:\s*#([0-9a-f]{6}|[0-9a-f]{3})\s*;?/i + ) { print "background color is $1"; }

    HTH
    ViceRaid

      Cheers for the help, folks. I aspire to Perl Enlightenment! A problem I'm having: I haven't used other modules' yet, as I'm having a download problem. The download manager shows that the file transfer is nearly complete, then states an error: the headers are invalid(?). I'm not sure what this means! I use PPM to install the modules, too. Cheers, R
Re: Background color HTML regexp
by gjb (Vicar) on Aug 22, 2003 at 14:58 UTC

    [0-9a-fA-F]{6} would be more precise.

    Hope this helps, -gjb-