Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

regex - Javascript Regular Expression for rgb values

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'm just looking to have:

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...