Home > Back-end >  regex to get all selector which have hex color code in its block but choose only one not all color
regex to get all selector which have hex color code in its block but choose only one not all color

Time:01-20

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;
}

`;
  1. using below regex I am able to get all the color code from css document
const rgx = /(?<color>#[0-9a-f]{3,6})/;

working demo fiddle

  1. now need to capture their repective selector used below regex which combine the above regex also in it
const rgx = /([.#]?[\w, .:] ?)(?= \{[^}] ?(?<color>#[0-9a-f]{3,6})[^}] ?\}.*)/;

working fiddle

but issue is with above regex is that it only capture the first hex valuie 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 her to get all color code ?

CodePudding user response:

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] 

CodePudding user response:

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)));
}

  • Related