Search code examples
regexperlstrip

Stripping/Substitution with Perl Regex


So I'm quite new to programming in general, so this may be a stupid question, but I am specifically trying to use regexes to strip a CSS tag. Basically I have this:

.style1 {  
    font-size: 24px;  
    font-weight: bold;  
    color: #FFEFA1;  
} 

and I want it to look like this:

.style1:color:#FFEFA1

I want to maintain the style name, color attributes, and color hex, with a colon in between and no spaces. I was attempting something like the following to make this happen:

$strip =~ s/\w+\}|\w+^#([0-9a-fA-F]{3})|([0-9a-fA-F]{6})//;

but it's not working. Anyone care to set me on the right path?

Cheers.


Solution

  • If you know that there will be a color attribute within $strip you can use

    $strip =~ s!\s*{.*color:\s*(#[0-9a-f]{6});.*}!:color:$1!is;
    

    Things to note:

    • i modifier does case insensitive matching
    • s modifier means that the '.' character matches any character including newlines