Check hex string contains only hexadecimal limited values

How to check the given sixth line, it contains only a hexadecimal number. is there any simple method or any java library for the same? I have a string like "01AF" and I need to check a string that contains only the hexadecimal values ​​of the range, since now I take the string and then split the string and then convert it to the appropriate format and then check that value. Is there any easy way to do this?

+3
source share
3 answers
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 a NumberFormatException if the hexadecimal string is not valid.

Refer to the documentation here

+3

, 0-9, a-h A-H,

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

, Pattern

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

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

Matcher

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

Indicated String stras your input line:

Option number 1:

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

Option number 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;
}
0
source

All Articles