Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex javascript to match both RGB and RGBA

Currently I have this regex which matches to an RGB string. I need it enhanced so that it is robust enough to match either RGB or RGBA.

rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/; //matches RGB

http://jsfiddle.net/YxU2m/

var rgbString =  "rgb(0, 70, 255)";
var RGBAString = "rgba(0, 70, 255, 0.5)";

var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/;
//need help on this regex
//I figure it needs to be ^rgba?, and then also an optional clause to handle the opacity

var partsRGB = rgbString.match(rgbRegex);
var partsRGBA = RGBAString.match(rgbRegex);

console.log(partsRGB); //["rgb(0, 70, 255)", "0", "70", "255"]
console.log(partsRGBA); //null. I want ["rgb(0, 70, 255, 0.5)", "0", "70", "255", "0.5"] 
like image 901
fortuneRice Avatar asked Sep 25 '11 05:09

fortuneRice


People also ask

What is global match in regex?

The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern. So the difference between /. +/g and /. +/ is that the g version will find every occurrence instead of just the first.

How do you match expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is global match in JavaScript?

Definition and Usage. The "g" modifier specifies a global match. A global match finds all matches (compared to only the first).

Does JavaScript support regex?

Using regular expressions in JavaScript. Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , replace() , search() , and split() . Executes a search for a match in a string. It returns an array of information or null on a mismatch.


3 Answers

Will this do?

var rgbRegex = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/
like image 182
Rusty Fausak Avatar answered Sep 18 '22 20:09

Rusty Fausak


It's not so simple- an rgb is illegal with a fourth parameter. You also need to allow for percentage decimals as well as integer values for the rgb numbers. And spaces are allowed almost anywhere.

function getRgbish(c){
    var i= 0, itm,
    M= c.replace(/ +/g, '').match(/(rgba?)|(\d+(\.\d+)?%?)|(\.\d+)/g);
    if(M && M.length> 3){
        while(i<3){
            itm= M[++i];
            if(itm.indexOf('%')!= -1){
                itm= Math.round(parseFloat(itm)*2.55);
            }
            else itm= parseInt(itm);
            if(itm<0 || itm> 255) return NaN;
            M[i]= itm;
        }
        if(c.indexOf('rgba')=== 0){
            if(M[4]==undefined ||M[4]<0 || M[4]> 1) return NaN;
        }
        else if(M[4]) return NaN;
        return M[0]+'('+M.slice(1).join(',')+')';
    }
    return NaN;
}

//testing:

var A= ['rgb(100,100,255)',
'rgb(100,100,255,.75)',
'rgba(100,100,255,.75)',
'rgb(100%,100%)',
'rgb(50%,100%,0)',
'rgba(100%,100%,0)',
'rgba(110%,110%,0,1)'];

A.map(getRgbish).join('\n');

returned values:
rgb(100,100,255)
NaN
rgba(100,100,255,.75)
NaN
rgb(127,255,0)
NaN
NaN
like image 45
kennebec Avatar answered Sep 19 '22 20:09

kennebec


I made a regex that checks for rgb() and rgba() values. It checks for 3 tuples of 0-255 and then an optional decimal number between 0-1 for transparency. TLDR;

rgba?\(((25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,\s*?){2}(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,?\s*([01]\.?\d*?)?\)

Broken into the different parts we have:

rgba?\( // Match rgb( or rgba( as the a is optional

0-255 is matched with alternation of:

\d\d? // Match 0-99

1\d\d // Match 100 - 199

2[0-4]\d // Match 200-249

25[0-5] // Match 250 - 255

The handling of comma and space around the 0-255 tuples takes some space. I match 0-255 tuples with mandatory trailing comma and optional spaces twice

(25[0-5]|2[0-4]\d|1([0-9]){1,2}|\d\d?)\s*,\s*){2}

Then a 0-255 tuple with optional comma and space - to allow for rgb() values without the trailing comma

(25[0-5]|2[0-4]\d|1([0-9]){1,2}|\d\d?),?\s*

Then comes an optional 0-1 as whole number or decimal number:

([01]\.?\d*?)? // 0 or 1 needed, dot and decimal numbers optional

And we end with a closing bracket

\)
like image 20
Pistus Avatar answered Sep 22 '22 20:09

Pistus