用于rgb值的Javascript正则表达式

cja*_*cja 12 javascript regex rgb

我正在尝试获取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);
Run Code Online (Sandbox Code Playgroud)

我只是想:

/// // I think I can pull these off by Starts With and Ends With anchors... ///
r = 'From "(" to "," ';
g = 'From "," to "," ';
b = 'From "," to ")" ';
Run Code Online (Sandbox Code Playgroud)

我正在尝试制作它,以便正则表达式可以采用1,2或3个数字,因为值从0到255.感谢您的帮助!

Ste*_*ley 19

下面是一些示例代码,它们应该大致满足您的需要或为您设置正确的方向:

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]);
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到它:http://jsfiddle.net/xonev/dRk8d/

  • @Strongwings:你的情况所需的正则表达式取决于可能出现的变化.我的正则表达式假设它非常虔诚地形成一个"rgb(#,#,#)"形式的字符串,不空格,没有间隙,只有三个数字包含在`rgb(...)`位中.史蒂文的版本在每个逗号后面都需要空格,并且不超过3位,同时,它允许字符串中的其他内容.我怀疑空间是你的输入和他的正则表达式的问题.arc的版本允许点之间的任何级别的间距.只需选择最简单的一个,以适应您的情况的变化. (2认同)

小智 10

我想出了这个"^(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(255,255,255)
  • rgb(255,255,255)rgb(0/0/0)
  • RGB(50-50-50)
  • rgb(0 - 0 - 0)
  • RGB(255,0-50)
  • rgb(0,255 255)
  • rgb(0 0 0)
  • 255,255,255
  • 255,255,0
  • (0,0,30)
  • (255 - 255 - 255)
  • rgb0 0 0
  • rgb255 - 0/255


小智 8

试试这个正则表达式:

/rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/
Run Code Online (Sandbox Code Playgroud)

它将r值捕获为$ 1,将g值捕获为$ 2,将b值捕获为$ 3


pim*_*vdb 8

给定一个字符串是有效的rgb,解析数字是一个匹配数字的问题:

"rgb(12, 34, 56)".match(/\d+/g); // ["12", "34", "56"]
Run Code Online (Sandbox Code Playgroud)