How to check if a string is a valid hex color code in android


I had a line that I need to check if this is a valid hex color code or not. My string lines are as follows:

1 - # ff00000

2 - # ff347820

How to check specified strings to check if they are valid hexadecimal color codes or not.
Can someone help me in solving this problem?


thanks in advance

+4
source share
3 answers

The right way to test Android, regardless of support for future formats, is to rely on the class Color.

Like this:

try {
    Color color = Color.parseColor(myColorString);
    // color is a valid color
} catch (IllegalArgumentException iae) {
    // This color string is not valid
}

, magenta, blue...

. myColorString String . - , , .

+13

, Pattern - , :

Pattern colorPattern = Pattern.compile("#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})");
Matcher m = colorPattern.matcher(yourInputString);
boolean isColor = m.matches();
+6
package com.javacodegeeks.java.core;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HexColorValidator {

private Pattern pattern;
private Matcher matcher;

private static final String HEX_PATTERN = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";

public HexColorValidator() {
    pattern = Pattern.compile(HEX_PATTERN);
}

public boolean validate(final String hexColorCode) {

    matcher = pattern.matcher(hexColorCode);
    return matcher.matches();

}
}

http://examples.javacodegeeks.com/core-java/util/regex/matcher/how-to-validate-hex-color-code-with-regular-expression/

+2

Source: https://habr.com/ru/post/1537099/


All Articles