const regex = /^rgba?\((?:(?:(?:[0-9]{1,3} ){2}[0-9]{1,3}|(?:[0-9]{1,3}% ){2}[0-9]{1,3}%)(?: \/ (?:[0-9]{1,3}%|1|0|0?\.[0-9]+))?|(?:(?:[0-9]{1,3}, ){2}[0-9]{1,3}|(?:[0-9]{1,3}%, ){2}[0-9]{1,3}%)(?:, (?:[0-9]{1,3}%|1|0|0?\.[0-9]+))?)\)$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^rgba?\\((?:(?:(?:[0-9]{1,3} ){2}[0-9]{1,3}|(?:[0-9]{1,3}% ){2}[0-9]{1,3}%)(?: \\\/ (?:[0-9]{1,3}%|1|0|0?\\.[0-9]+))?|(?:(?:[0-9]{1,3}, ){2}[0-9]{1,3}|(?:[0-9]{1,3}%, ){2}[0-9]{1,3}%)(?:, (?:[0-9]{1,3}%|1|0|0?\\.[0-9]+))?)\\)$', 'gm')
const str = `// invalid
rgb()
rgba()
rgb(123)
rgb(11 22 )
rgb(11 22 2 / 03)
rgb(11 22 2 / 10)
rgb(1 2 3 / 0.34%)
rgb(11% 22 33)
rgb(111 222% 333)
rgb(1 22 333 )
rgb(1 2 3, 1)
rgb(1 2, 3 / 1)
// valid
rgb(111 22 333)
rgb(1 2 3)
rgb(11 22 33)
rgb(111 222 333)
rgb(1 22 333)
rgb(1 2 3 / 1)
rgb(11 22 2 / 0)
rgb(1 2 3 / 0.34)
rgb(1 2 3 / .34)
rgb(1 2 3 / 0.34)
rgb(1 2 3 / 1%)
rgb(1 2 3 / 10%)
rgb(1 2 3 / 100%)
rgb(11 22 2 / 0%)
rgb(1 2 3 / 34%)
rgb(1 2 3 / 4%)
rgb(111 22 333)
rgb(1% 2% 3%)
rgb(11% 22% 2% / 0)
rgb(12%, 0%, 100%)
rgb(111, 22, 333)
rgb(1, 2, 3)
rgb(1, 2, 3, 1)
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions