正则表达式javascript匹配RGB和RGBA [英] regex javascript to match both RGB and RGBA

查看:2846
本文介绍了正则表达式javascript匹配RGB和RGBA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有这个与RGB字符串匹配的正则表达式。我需要它增强,以便它足够强大以匹配RGB或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"] 


推荐答案

这不是那么简单 - 使用第四个参数rgb是非法的。
您还需要允许百分比小数以及rgb数字的整数值
。几乎可以在任何地方使用空间。

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

//测试:

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

这篇关于正则表达式javascript匹配RGB和RGBA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆