Question

How to check a given hex string contains only hex number. is there is any simple method or any java library for the same?i have string like "01AF" and i have to check string only contains hex range values,for that what i am doing now is take the string and then split the string and then converted it to appropriate format then make a check for that value.is there is any simple method for that?

Was it helpful?

Solution

try
{
    String hex = "AAA"
    int value = Integer.parseInt(hex, 16);  
    System.out.println("valid hex);
 }
 catch(NumberFormatException nfe)
 {
    // not a valid hex
    System.out.println("not a valid hex);
 }

This will throw NumberFormatException if the hex string is invalid.

Refer the documentation here

OTHER TIPS

If you want to check if string contains only 0-9, a-h or A-H you can try using

yourString.matches("[0-9a-fA-F]+");

To optimize it you can earlier create Pattern

Pattern p = Pattern.compile("[0-9a-fA-F]+");

and later reuse it as

Matcher m = p.matcher(yourData);
if (m.matches())

and even reuse Matcher instance with

m.reset(newString);
if (m.matches())

Given String str as your input string:

Option #1:

public static boolean isHex(String str)
{
    try
    {
        int val = Integer.parseInt(str,16);
    }
    catch (Exception e)
    {
        return false;
    }
    return true;
}

Option #2:

private static boolean[] hash = new boolean[Character.MAX_VALUE];
static // Runs once
{
    for (int i=0; i<hash.length; i++)
        hash[i] = false;
    for (char c : "0123456789ABCDEFabcdef".toCharArray())
        hash[c] = true;
}
public static boolean isHex(String str)
{
    for (char c : str.toCharArray())
        if (!hash[c])
            return false;
    return true;
}

If anyone reached this thread trying to avoid the following exception when parsing a Mongodb ObjectId:

java.lang.IllegalArgumentException: invalid hexadecimal representation of an ObjectId: [anInvalidId]

Then note this utility method offered by the mongo-java-driver library:

ObjectId.isValid(stringId)

Related thread:

How to determine if a string can be used as a MongoDB ObjectID?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top