我正在尝试获取rgb字符串的各个值。我一直在接近,但我只是撞墙了。我想做这样的事情:
var color = rgb(255, 85, 120);
/// My Regex ///
var rRegex = /^rgb\(\d{3}/; // Which actually gives me an array of two strings...ugh
var gRegex = ;
var bRegex = ;
var r = color.match(rRegex);
var g = color.match(gRegex);
var b = color.match(bRegex);
我只是想:
/// // I think I can pull these off by Starts With and Ends With anchors... ///
r = 'From "(" to "," ';
g = 'From "," to "," ';
b = 'From "," to ")" ';
我正在尝试制作它,以便正则表达式可以采用1,2或3个数字,因为值从0到255.感谢您的帮助!
下面是一些示例代码,它们应该按照您的需要进行操作,或者为您设置正确的方向:
var color = 'rgb(255, 15, 120)';
var matchColors = /rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/;
var match = matchColors.exec(color);
if (match !== null) {
document.write('Red: ' + match[1] + ' Green: ' + match[2] + ' Blue: ' + match[3]);
}
你可以在这里看到它:http://jsfiddle.net/xonev/dRk8d/
我想出了这个"^(rgb)?\(?([01]?\d\d?|2[0-4]\d|25[0-5])(\W+)([01]?\d\d?|2[0-4]\d|25[0-5])\W+(([01]?\d\d?|2[0-4]\d|25[0-5])\)?)$"
,它可以验证一大堆字符串变体,包括:
试试这个正则表达式:
/rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/
它将r值捕获为$ 1,将g值捕获为$ 2,将b值捕获为$ 3
给定一个字符串是有效的rgb,解析数字是一个匹配数字的问题:
"rgb(12, 34, 56)".match(/\d+/g); // ["12", "34", "56"]
我用这个:rgb\(\s*(?:(?:\d{1,2}|1\d\d|2(?:[0-4]\d|5[0-5]))\s*,?){3}\)$
rgb
{3}
它意味着我们将检查3次以下的条件\d{1,2}
如果里面的值只有1或2个符号 - 检查是否有数字1\d\d
如果里面的值有3位数,第一个等于1
,其余的是数字2(?:[0-4]\d|5[0-5])
如果里面的值有3位数,那么第一个等于2
?:[0-4]\d
如果第二个符号在0-4
的范围内,第三个符号应该是任何数字
5[0-5]
如果第二个符号等于5
那么第三个符号应该是0-5
范围内的数字^(\ d {1,2} | [1] [0-9] [0-9] | [2] [0-5] [0-5]);(\ d {1,2} | [1 ] [0-9] [0-9] | [2] [0-5] [0-5]);(\ d {1,2} | [1] [0-9] [0-9] | [2] [0-5] [0-5])$
格式x; x; x其中x是0(包括)和255(包括)之间的数字
试试这个。范围在0到255之间的正则表达式。
rgb\((( *0*([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]) *),){2}( *0*([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]) *)\)
function rgb(value) {
if (typeof value !== 'string') {
return false;
}
return value.match(new RegExp('^rgb\\((25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9])\\)$')) !== null;
}
function rgba(value) {
if (typeof value !== 'string') {
return false;
}
return value.match(new RegExp('^rgba\\((25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(1|0|0\.[0-9]+)\\)$')) !== null;
}
例子:
'rgb(255,255,255)' // true
'rgb(255, 255,255)' // true
'rgb(255, 255, 255)' // true
'rgb(0,0,0)' // true
'rgb(255,255,255)' // true
'rgb(256,255,255)' // false, min: 0, max: 255
'rgb(01,1,1)' // false, zero is not accepted on the left, except when the value was exactly 0 (here 0 != 00)