Programming Tips - Java: Test if a string is all hexadecimal characters

Date: 2010aug31 Update: 2025sep29 Language: Java Keywords: hex Q. Java: Test if a string is all hexadecimal characters A. There are many ways but I think the nicest is using Pattern's {XDigit} As shown in this full example:
class Demo { static boolean isAllHex(final String s) { return s.matches("\\p{XDigit}+"); } public static final void main(String []args) { { var str = "12345"; System.out.println("is '" + str + "' all hex=" + isAllHex(str)); } { var str = "abcdef"; System.out.println("is '" + str + "' all hex=" + isAllHex(str)); } { var str = "abcdefg"; System.out.println("is '" + str + "' all hex=" + isAllHex(str)); } } }
Output:
is '12345' all hex=true is 'abcdef' all hex=true is 'abcdefg' all hex=false