Javascript Regular Expression for rgb values

后端 未结 9 1232
名媛妹妹
名媛妹妹 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:47
    function rgb(value) {
      if (typeof value !== 'string') {
        return false;
      }
    
      return value.match(new RegExp('^rgb\\((25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9])\\)$')) !== null;
    }
    
    function rgba(value) {
      if (typeof value !== 'string') {
        return false;
      }
    
      return value.match(new RegExp('^rgba\\((25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?|[0-9]), ?(1|0|0\.[0-9]+)\\)$')) !== null;
    }
    

    Examples:

    'rgb(255,255,255)' // true
    'rgb(255, 255,255)' // true
    'rgb(255, 255, 255)' // true
    'rgb(0,0,0)' // true
    'rgb(255,255,255)' // true
    'rgb(256,255,255)' // false, min: 0, max: 255
    'rgb(01,1,1)' // false, zero is not accepted on the left, except when the value was exactly 0 (here 0 != 00)
    
    0 讨论(0)
  • 2020-12-18 21:52

    I have come up with this "^(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])\)?)$" which can validate a whole heap of string variations including:

    • 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
    0 讨论(0)
  • 2020-12-18 21:53

    Given a string is valid rgb, parsing numbers out it is a matter of matching digits:

    "rgb(12, 34, 56)".match(/\d+/g); // ["12", "34", "56"]
    
    0 讨论(0)
提交回复
热议问题