How to convert #ffffff to #fff or #fff to #ffffff while asserting the background color rgb(255,255,255) returned by Selenium getCssValue(“background”)

前端 未结 2 1369
孤城傲影
孤城傲影 2021-01-21 09:00

How to convert #ffffff to #fff or #fff to #ffffff for Assertion?

I am using getCssValue(\"background\") from Sele

2条回答
  •  一整个雨季
    2021-01-21 09:39

    You can use replaceAll with a regular expression that looks for the case where all three parts use the same digit:

    static String getHex(int r, int g, int b) {
        return String.format("#%02x%02x%02x", r, g, b).replaceAll("^#([a-fA-F])\\1([a-fA-F])\\2([a-fA-F])\\3$", "#$1$2$3");
    }
    

    That looks for a string starting with # followed by three pairs of matching hex digits, and replaces them with just the short form. (I suppose I could have just used [a-f] instead of [a-fA-F] in your specific example, since you know you'll be getting lower case only, but...)

    Complete example (on Ideone):

    public class Example {
        public static void main(String[] args) {
            System.out.println(getHex(255, 255, 255)); // #fff
            System.out.println(getHex(255, 240, 255)); // #fff0ff
        }
    
        static String getHex(int r, int g, int b) {
            return String.format("#%02x%02x%02x", r, g, b).replaceAll("^#([a-fA-F])\\1([a-fA-F])\\2([a-fA-F])\\3$", "#$1$2$3");
        }
    }
    

提交回复
热议问题