Javascript Regular Expression for rgb values

后端 未结 9 1231
名媛妹妹
名媛妹妹 2020-12-18 21:15

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:

v         


        
相关标签:
9条回答
  • 2020-12-18 21:31

    Try this regex:

    /rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/
    

    It will capture the r value into $1, the g value into $2, and the b value into $3

    0 讨论(0)
  • 2020-12-18 21:35

    I use this one: rgb\(\s*(?:(?:\d{1,2}|1\d\d|2(?:[0-4]\d|5[0-5]))\s*,?){3}\)$

    • prefix is rgb
    • at the end we have {3} it means we will checks conditions from below 3 times

    • \d{1,2} if value inside have only 1 or 2 symbols - check if there are digits

    • 1\d\d if value inside have 3 digits and first one is equals to 1 and rest of them are digits

    • 2(?:[0-4]\d|5[0-5]) if value inside have 3 digits and first one is equals to 2 then
      • ?:[0-4]\d if second symbol is in range of 0-4 the third one should any digit
      • 5[0-5] if second symbol is equals to 5 then third symbol should be digit from range 0-5
    0 讨论(0)
  • 2020-12-18 21:41

    Try this. A regex within the range 0 - 255.

    rgb\((( *0*([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]) *),){2}( *0*([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]) *)\)
    

    Regular expression visualization

    Debuggex Demo

    0 讨论(0)
  • 2020-12-18 21:42
    ^(\\d{1,2}|[1][0-9][0-9]|[2][0-5][0-5]);(\\d{1,2}|[1][0-9][0-9]|[2][0-5][0-5]);(\\d{1,2}|[1][0-9][0-9]|[2][0-5][0-5])$ 
    

    format x;x;x where x is a number between 0 (included) and 255 (included)

    0 讨论(0)
  • 2020-12-18 21:43

    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/

    0 讨论(0)
  • 2020-12-18 21:43

    Typescript solution:

    interface RGB {
      r: number,
      g: number,
      b: number
    }
    
    const str2rgb = (color: string): RGB => {
      const rgbSubset = color
        .split('(')
        .pop()
        ?.split(')')
        .shift()
        ?.split(',')
        .slice(0, 3)
        .map(Number);
    
      if (rgbSubset && rgbSubset.length === 3) {
        const [r, g, b] = rgbSubset;
        return {r, g, b};
      }
    
      throw new Error(`Invalid color = ${color}`);
    };
    
    
    0 讨论(0)
提交回复
热议问题