1

I have a big CSS file with all CSS we need for our internal framework, but I only need a few of the styles. So I want to extract the style I want. I used regular expression to extract them:

cssFileContent.scan(/\.#{cssName}.*?\{.+?\}/im)

In Ruby, scan means extract the patter from string, cssName is the CSS style name i - case insensitive m - dot match everything so that \n will be matched too

It gives me some style blocks, but skip one every time. For example, I have .abc-style { } and .def-style { }, but result is like:

.abc-style {

}

}

so def-style is skipped.

Can someone give me any point why? And how to correct?

2 Answers 2

3

Instead of using a regex I would use a CSS parser to do this.

There are plenty on CPAN to chose from, for e.g. CSS, CSS::SAC, CSS::Tiny & CSS::Croco. Choose the one which best fits your needs.

Here is an example using CSS::Tiny...

use strict;
use warnings;
use CSS::Tiny;

my $css = CSS::Tiny->read('your_stylesheet.css');
my $new = CSS::Tiny->new;

# styles I want to extract
$new->{$_} = $css->{$_} for qw/.abc-style .def-style/;

$new->write('extracted_styles.css');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the alternative :)
2

Try excluding the closing bracket and make the collection greedy like this:

cssFileContent.scan(/\.#{cssName}.*?\{[^\}]+\}/im)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.