用于rgb值的Javascript正则表达式 [英] Javascript Regular Expression for rgb values

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

问题描述

我正在尝试获取rgb字符串的各个值。我一直在接近,但我只是撞墙了。我希望做这样的事情:

I'm trying to get the individual values of a rgb string. I've been getting close, but I'm just hitting a wall. I'm looking to do something like this:

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.感谢您的帮助!

I'm trying to make also make it so that the regex can take either 1, 2, or 3 numbers, as the values go from 0 - 255. Thanks for any help!

推荐答案

这是一些示例代码应该做的大概是什么你需要或设置正确的方向:

Here is some example code that should do approximately what you need or set you in the right direction:

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/

You can see it in action here: http://jsfiddle.net/xonev/dRk8d/

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

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