Reputation: 54016
requirement: collect all color codes ( in hex format for now) from a CSS document along with their selector.
below is the sample css document
const cssDcoument = `
body {
padding: 2px;
background-color: #111;
color: #222;
}
main {
margin: 20px;
border: 1px solid red;
}
.class, .other {
color: #333;
font-size: 20px;
}
`;
const rgx = /(?<color>#[0-9a-f]{3,6})/;
const rgx = /([.#]?[\w, .:]+?)(?= \{[^}]+?(?<color>#[0-9a-f]{3,6})[^}]+?\}.*)/;
but issue is with above regex is that it only capture the first hex value property from one block not all like the first regex does.
here only select #111
but not #222
from body
selector
what can be done here to get all color code ?
Upvotes: 0
Views: 130
Reputation: 2861
Search for blocks with rules first, then for particular colors:
const css = `
body {
padding: 2px;
background-color: #111;
color: #222;
}
main {
margin: 20px;
border: 1px solid red;
}
.class, .other {
color: #333;
font-size: 20px;
}
`;
const matches = css.matchAll(/^\s?(.+)\{([^}]+|\s+)}/gm);
for (const match of matches) {
console.log("selector", match[1].trim());
const block = match[2].trim();
console.log(block.match((/#([a_fA-F0-9]{3,6})/g)));
}
Upvotes: 1
Reputation: 1024
Use the following regex to get color specifically
^\s*color\:\s*\#[a-fA-F0-9]+
To get any line with color in it:
color\:\s*\#[a-fA-F0-9]+
positive lookbehind
(?<=color)\:\s*\#[a-fA-F0-9]+
Upvotes: 0