0

如果有人能指出我正确的方向,我将不胜感激。我有一个数组“cArr”,在这个数组中我有 2 个元素。我想做的是匹配“rgb(xx,xx,xx)”并将其推送到数组“rgbArr”;我遇到的问题是正则表达式。

这是我的代码:

var cArr = ["id0{shape:round,rgb(24,23,12)}","id1{shape:long,weight:heavy,rgb(20,20,20)}","id2{shape:elongated,weigth:light,rgb(15,24,8)}"];


for(var i=cArr.length -1; i>=0; i--)
{
  if(cArr[i].match(matchColors))
  {
    rgbArr.push(cArr[i]);
    break;
  }
}

console.log(rgbArr);
4

2 回答 2

2

I was wrestling with this issue today and have a slightly more simplified solution to this issue which uses a slightly different Regular Expression along with JavaScripts 'match' function (I have wrapped it up in a function so that we can reuse this functionality as required):

function parseRGB ( string ) {
    var rgbRegex = /(rgb\([^)]*\))/gi;
    var rgbArray = string.match(rgbRegex); 

    return rgbArray;
}

Now simply call the function with the value you want to check. E.g.

parseRGB( '-moz-linear-gradient( top, rgb(68, 68, 68), rgb(153, 153, 153))' );

Which will return the following array:

[ "rgb(68, 68, 68)", "rgb(153, 153, 153)" ]   

A few things to note:

  • If no RGB matches are found this function will return null.
  • JavaScripts match string function will automatically put all occurances into an array for you. It can take a regular expression as a parameter.
  • This can handle multiple rgb values if they exist in the string to be checked.

Hope this helps someone.

于 2012-10-18T13:01:59.820 回答
1

请澄清您的问题(似乎我在上面的评论),暂时尝试这样的事情。(但这并没有为您提供第一个元素中的多种 rgb 颜色......)

var matchColors=/.*?(rgb\([^)]*\)).*/;

var cArr = ["id0{shape:round,rgb(24,23,12)},id1{shape:long,weight:heavy,rgb(20,20,20)}","id2{shape:elongated,weigth:light,rgb(15,24,8)}","sdf"];

var rgbArr=[];

for(var i=cArr.length -1; i>=0; i--) {
    if(cArr[i].match(matchColors)) {
        var x = cArr[i].replace(matchColors,"$1");
        rgbArr.push(x);
//      break;
    }
}

console.log(rgbArr);​
于 2012-05-16T07:06:14.120 回答