2

如果我有字符串rgba(111,222,333,0.5),我如何从字符串中提取单个颜色,即

red => 111
green => 222
blue => 333
opacity => 0.5

我希望能够为此使用一个简洁干净的解决方案,所以我假设正则表达式是最好的?

4

6 回答 6

10

对于可预测的字符串,我会避免使用正则表达式,并建议:

// assigning the rgb() colour to a variable:
var colorString = "rgba(111,222,333,0.5)",

    // using String.prototype.substring() to retrieve
    // the substring between the indices of the opening
    // and closing parentheses:
    colorsOnly = colorString.substring(
        // here we find the index of the opening
        // parenthesis, and add 1 to that index
        // so that the substring starts after that
        // parenthesis:
        colorString.indexOf('(') + 1,

        // and terminating the substring at the
        // index of the closing parenthesis:
        colorString.lastIndexOf(')')
      // here we split that substring on occurrence
      // of a comma followed by zero or more white-
      // space characters:
      ).split(/,\s*/),

    // String.prototype.split() returns an Array,
    // here we assign those Array-elements to the
    // various colour-, or opacity-, variables:
    red = colorsOnly[0],
    green = colorsOnly[1],
    blue = colorsOnly[2],
    opacity = colorsOnly[3];

JS 小提琴演示

或者,假设您希望返回一个对象:

var colorString = "rgba(111,222,333,0.5)",
  colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
  // here we initialise an empty Object:
  components = {};
// here we assign the Array-elements to the
// named properties of that Object:
components.red = colorsOnly[0];
components.green = colorsOnly[1];
components.blue = colorsOnly[2];
components.opacity = colorsOnly[3];

console.log(colorsOnly, components);

JS 小提琴演示

编辑为使用更现代的 JavaScript:

const colorString = "rgba(111,222,333,0.5)",
  // here we use destructuring assignment to assign the returned Array-elements
  // - in respective order - to the named variables:
  [red, green, blue, opacity] = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
  // passing the variables into the Object Literal; in this instance
  // we're passing in the variables which are the literal name of the
  // properties they define and which also contain the relevant value:
  colorObject = {
    red,
    green,
    blue,
    opacity
  };
console.log(red, green, blue, opacity, colorObject);

参考:

于 2012-09-10T16:00:11.157 回答
3

正则表达式将是:

^rgba\(([^,]+),([^,]+),([^,]+),([^,]+)\)$

Javascript代码:

var regex = /^rgba\(([^,]+),([^,]+),([^,]+),([^,]+)\)$/g; 
var input = "rgba(111,222,333,0.5)"; 
if(regex.test(input)) {
  var matches = input.match(regex);
  for(var match in matches) {
    alert(matches[match]);
  } 
} else {
  alert("No matches found!");
}

您可能希望修剪匹配项和/或将值转换为数字以在 JavaScript 中获取所需的 RGBA 值。

在RegexHero玩这个

如果您想处理正则表达式本身的参数之间的空格,它可能会开始看起来像这样丑陋:

^rgba\(\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*\)$
于 2012-09-10T15:56:26.440 回答
3

使大卫更简单和解释

 var colorString = "rgba(111,222,333,0.5)";
 var colorsOnly = colorString.split(")"); //gives "rgba(111,222,333,0.5" at index 0
 var colorsOnly = colorString[0].split("(");   //gives "111,222,333,0.5 at index 1
 var colorsOnly = colorString[1].split(","); 

在 [0] 处给出“111”,在 [1] 处给出“222”,在 [2] 处给出“333”,在 [3] 处给出“0.5”,但注意:所有这些都具有字符串数据类型,因为所有这些都是子字符串。

red = parseInt(colorsOnly[0]);
green = parseInt(colorsOnly[1]);
blue = parseInt(colorsOnly[2]);
opacity = parseFloat(colorsOnly[3]);

使用parseInt()parseFloat()方法将字符串分别转换为整数和浮点数。

于 2014-04-22T09:55:36.273 回答
0

对于 Ahmed Bilal 的回答,我有一些需要纠正的地方。如果我错了,也请随时纠正我!:)

它应该是:

    var colorsOnly = colorString.split(")");
    var colorsOnly = colorString.split("(");
    var colorsOnly = colorsOnly[1].split(",");      

注意第四句的变化。由于第三句中的 ColosOnly 代表了“(”拆分后的结果。所以我认为应该colorsOnly[1]在第三句中。我自己尝试过并得到了证明。

再次,如果我错了,也请随时纠正我!:)

于 2014-11-07T00:16:28.913 回答
0

这是另一种解决方案。

const rgbaStrToValues = function( rgba ) {
    const realNumPattern = '([+-]?\\d*\\.?\\d+)';
    const rgbaPattern = `rgba?\\(` +
        ` *${ realNumPattern } *, *${ realNumPattern } *,` +
        ` *${ realNumPattern } *(?:, *${ realNumPattern } *)?\\)`;
    const regexp = new RegExp( rgbaPattern );
    const result = regexp.exec( rgba );
    if ( ! result ) { return; }

    const { 1: red, 2: green, 3: blue, 4: alpha } = result;
    if ( ! ( red && green && blue ) ) { return; }

    const { min, max } = Math;
    return {
        red  : max( min( Number( red ), 255 ), 0 ),
        green: max( min( Number( green ), 255 ), 0 ),
        blue : max( min( Number( blue ), 255 ), 0 ),
        alpha: alpha ? max( min( Number( alpha ), 1 ), 0 ) : 1,
    };
};

rgbaStrToValues( 'rgba( 111, 222, 333, 0.5 )' );

我用日语写了这段代码的描述

于 2020-09-14T01:41:40.493 回答
-1

如果它始终采用 rgba 格式,您可以执行以下操作:

var str = 'rgba(111,222,333,0.5)'

var red = str.substr(5,3);
var green = str.substr(9,3);
var red = str.substr(13,3);
于 2012-09-10T16:00:01.843 回答