正则表达式 javascript 匹配 RGB 和 RGBA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7543818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:28:41  来源:igfitidea点击:

regex javascript to match both RGB and RGBA

javascriptregexrgbrgba

提问by fortuneRice

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.

目前我有这个与 RGB 字符串匹配的正则表达式。我需要对其进行增强,使其足够强大以匹配 RGB 或 RGBA。

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

http://jsfiddle.net/YxU2m/

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"] 

回答by Rusty Fausak

Will this do?

这会吗?

var rgbRegex = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/

回答by kennebec

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.

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

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

回答by Pistus

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;

我做了一个正则表达式来检查 rgb() 和 rgba() 值。它检查 0-255 的 3 个元组,然后检查 0-1 之间的可选十进制数以确保透明度。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:

0-255 与以下交替匹配:

\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

处理 0-255 元组周围的逗号和空格需要一些空间。我将 0-255 个元组与强制尾随逗号和可选空格匹配两次

(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

然后是一个带有可选逗号和空格的 0-255 元组 - 允许 rgb() 值没有尾随逗号

(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:

然后是一个可选的 0-1 作为整数或十进制数:

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

And we end with a closing bracket

我们以一个结束括号结束

\)

回答by mihai

If you need to be strict, i.e. rule out rgb(0, 70, 255, 0.5), you need to fuse both cases together with | :

如果您需要严格,即排除 rgb(0, 70, 255, 0.5),则需要将这两种情况与 | 融合在一起。:

var rgbRegex = /(^rgb\((\d+),\s*(\d+),\s*(\d+)\)$)|(^rgba\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+\.\d+)*\)$)/; 

http://jsfiddle.net/YxU2m/2/

http://jsfiddle.net/YxU2m/2/

回答by vipmaa

i use this it is help

我用这个是有帮助的

(.*?)(rgb|rgba)\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/i

if you check rgba(102,51,68,0.6)

如果你检查 rgba(102,51,68,0.6)

it will return

它会回来

1.  [0-0]   ``
2.  [0-4]   `rgba`
3.  [5-8]   `102`
4.  [9-11]  `51`
5.  [12-14] `68`
6.  [15-18] `0.6`

and if you check rgb(102,51,68)

如果你检查 rgb(102,51,68)

it will return

它会回来

1.  [21-21] ``
2.  [21-24] `rgb`
3.  [25-28] `102`
4.  [29-31] `51`
5.  [32-34] `68`

回答by Votemike

This regex is a good compromise between the complexity of the regex and number of use-cases covered.

这个正则表达式是正则表达式的复杂性和涵盖的用例数量之间的一个很好的折衷。

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

rgb and rgba need to be treated differently as one needs the 4th argument and one doesn't.

rgb 和 rgba 需要区别对待,因为需要第 4 个参数而不需要。

This regex takes that into account. It also deals with:

这个正则表达式考虑到了这一点。它还涉及:

  • 1, 2 or 3 digit rgb values
  • rgb values under 0 and over 255
  • (some) spaces
  • a 4th value missing from rgba
  • a 4th value in rgb
  • 1、2 或 3 位 rgb 值
  • rgb 值小于 0 和大于 255
  • (一些)空格
  • rgba 中缺少第四个值
  • rgb 中的第四个值

This regex does not take into account:

此正则表达式不考虑:

  • every legal type of spacing
  • percentage based rgb values
  • 每种合法的间距类型
  • 基于百分比的 rgb 值

回答by GibboK

Try the following script for RGBA value, the result is an object.

尝试使用以下脚本获取 RGBA 值,结果是一个对象。

       var getRGBA = function (string) {
          var match = string.match(/^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d*(?:\.\d+)?)\)$/);
          return match ? {
            r: Number(match[1]),
            g: Number(match[2]),
            b: Number(match[3]),
            a: Number(match[4])
          } : {}
        };
                           
        var rgba = getRGBA('rgba(255, 255, 255, 0.49)');
        console.log(rgba);

回答by user3753974

For patterns: rbga(12,123,12,1) rbga(12,12,12, 0.232342) rgb(2,3,4)

对于模式: rbga(12,123,12,1) rbga(12,12,12, 0.232342) rgb(2,3,4)

/^(rgba|rgb)\(\s?\d{1,3}\,\s?\d{1,3}\,\s?\d{1,3}(\,\s?(\d|\d\.\d+))?\s?\)$/

回答by Arman Petrosyan

Another version to support rgb and rgba separately , with not strict spaces and allowing pattern rgba(255,255,255, .5)

另一个分别支持 rgb 和 rgba 的版本,没有严格的空格并允许模式 rgba(255,255,255, .5)

(rgb\((((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*?)?\))|(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*(0?\.\d*|0(\.\d*)?|1)?\))