I\'d like to parce a CSS file and add before every CSS selector another selector.
From:
p{margin:0 0 10px;}
.lead{margin-bottom:20px;font-size:21px;font-
Faced a similar problem and used the following to extract only CSS selectors and directives without comments and media queries:
/^(?!.*@media)[\t ]*([a-zA-Z#.:*\[][^{\/]*\s*){[\s\S]*?}/
Example: https://regex101.com/r/JmjthP/5
I'm sure it's missing some edge-cases but seems to be working for me.
See this question: Ruby RegExp - Match all CSS selectors and directives
There isn't one. CSS selectors are not an example of a "Regular Language" and so cannot be parsed by a Regular Expression. You will need to build your own parser based on the CSS grammar specification: http://www.w3.org/TR/css3-syntax/#detailed-grammar
CSS is described as an LL(1) grammar, so you're probably better off using a tool like Yacc to generate your parser for you.
While it isn't possible to write a single regular expression that matches any valid CSS selector, you can combine a couple regular expressions and a bit of logic to accomplish your goal.
The following uses Node's fs
module to read the CSS, but you could get the raw CSS string however you want.
const fs = require('fs'),
myClassName = 'mySelector',
mySelector = '.' + myClassName,
mySelectorRegex = new RegExp(`\\.${myClassName}([ .#[:(]|$)`),
cssSelectorRegex = /[@.#a-zA-Z][^}]*?(?={)/g;
let css = fs.readFileSync('path/to/file.css').toString();
css = css.replace(cssSelectorRegex, match => {
// Match is a string of selectors like '.foo' or '.foo, #bar'
// We need to split it on the comma and handle each selector individually
return match.split(',').map(selector => {
selector = selector.trim();
// Don't alter media queries, imports, or selectors that already contain '.mySelector'
if (selector.startsWith('@') || selector.match(mySelectorRegex)) {
return selector;
}
// Prepend '.mySelector ' to the selector
return mySelector + ' ' + selector;
// Combine the list of selectors back together
}).join(',');
});